0% found this document useful (0 votes)
3 views17 pages

Python File Handling Notes

This document provides comprehensive revision notes on Python file handling, covering core concepts, file modes, syntax references, and practical code examples. It includes a mini project for creating a student grade book, highlighting functions for adding, viewing, and searching for students, as well as common mistakes and best practices in file operations. Key topics include the importance of using files for data persistence, different file modes for reading and writing, and error handling techniques.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views17 pages

Python File Handling Notes

This document provides comprehensive revision notes on Python file handling, covering core concepts, file modes, syntax references, and practical code examples. It includes a mini project for creating a student grade book, highlighting functions for adding, viewing, and searching for students, as well as common mistakes and best practices in file operations. Key topics include the importance of using files for data persistence, different file modes for reading and writing, and error handling techniques.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python — Reading & Writing Files ■

Comprehensive Revision Notes • VS Code Light Theme

■ Contents

# Section Topic

01 Core Concept What are files? Why use them?

02 File Modes r, w, a, r+ — when to use each

03 Syntax Reference All methods & string tools

04 Code Examples Write, Read, Append, try/except, enumerate

05 Mini Project Student Grade Book — full annotated code

06 Mistakes I Made 4 mistakes — wrong vs correct

07 Things to Remember 10 quick-revision rules

Python File Handling — Revision Notes Page 1


01 — Core Concept: What Are Files?
When a Python program runs, all data it creates lives in RAM (temporary memory). The moment the program
stops, that data is gone forever. Files solve this — they let you save data permanently on disk so it survives
after your program ends.

■ Analogy
Think of RAM like a whiteboard — fast, but erased when you're done. A file is like a notebook — slower to write,
but permanent.

The Three-Step Workflow

Step Action Code

1 Open the file open("[Link]", "mode")

2 Read or Write [Link]() / [Link](...)

3 Close the file [Link]()

■ Best Practice
The with statement (see Section 03) handles Step 3 automatically — you never have to call [Link]() manually.
Always prefer it.

Real-World Uses of File Handling

• Saving user data, settings, or preferences


• Logging events or errors from a program
• Reading datasets (CSV files) for data science
• Writing output reports or results
• Loading configuration files for applications

Python File Handling — Revision Notes Page 2


02 — File Modes
The second argument of "open()" is the mode. It tells Python what you want to do with the file.

Mode What it does File missing? When to use

"r" Read only ■ Error if missing Most common — safe, cannot overwrite

"w" Write (overwrite) ■ Creates new file ■ Destroys old content!

"a" Append (add to end) ■ Creates new file Safe — old data preserved

"r+" Read AND write ■ Error if missing For editing existing files

"rb" Read binary ■ Error if missing Images, PDFs, non-text files

"wb" Write binary ■ Creates new file Saving binary files

■■ Warning
"w" is the most dangerous mode — it silently deletes existing content and creates a fresh file. If you want to add
data without losing the old, always use "a".

Python File Handling — Revision Notes Page 3


03 — Syntax Reference

File Methods

Method What it does

[Link]() Returns entire file content as ONE string

[Link]() Reads ONE line (including \n)

[Link]() Returns a LIST — each line is one item

[Link](text) Writes a string (does NOT add \n automatically)

[Link](list) Writes a list of strings (no auto \n either)

[Link]() Closes and saves the file — not needed with with

[Link](0) Moves cursor back to start of file

[Link]() Returns current cursor position (number of bytes)

Essential String Tools Used With Files

Tool / Syntax What it does

.strip() Removes leading/trailing whitespace AND \n

.rstrip() Removes only trailing whitespace/\n

.lstrip() Removes only leading whitespace

.split(',') Splits string at each comma → returns a list

.lower() Converts string to all lowercase

.upper() Converts string to all uppercase

'\n' Newline character — moves to next line in a file

f-string f"Name: {name}" — embeds variables inside strings

Other Key Concepts Used in This Topic

Concept Meaning

enumerate(list, start) Loop giving both index and item simultaneously

try / except Catches errors so the program doesn't crash

FileNotFoundError Exception raised when file doesn't exist in 'r' mode

ValueError Exception raised when wrong data type is given

flag variable Boolean (True/False) to track if something was found

break Exits a loop immediately

Python File Handling — Revision Notes Page 4


continue Skips rest of current loop iteration, goes back to top

while True: Infinite loop — keep running until break is hit

Python File Handling — Revision Notes Page 5


04 — Code Examples

Example 1 — Write to a File (basic)

write_basic.py

# Step 1: Open (or create) a file in write mode

file = open ("my_notes.txt" , "w" )

# Step 2: Write a string into it

file .write ("Hello! This is my first file." )

# Step 3: Always close the file

file .close ()

■ Tip
After running this, a file called my_notes.txt appears in the same folder as your script. Open it in any text editor to
verify!

Example 2 — The BETTER Way: with Statement

write_with.py

# "with" automatically closes the file when the block ends

# No need to call [Link]() ever again!

with open ("my_notes.txt" , "w" ) as file :

file .write ("Line one\n" )

file .write ("Line two\n" )

# File is safely closed here — even if an error occurs inside

■ Tip
Think of with like a library — it opens the door, you do your work, and it locks the door automatically when you
leave. No chance of forgetting!

Example 3 — Read a File

read_file.py

# read() returns the ENTIRE file as one big string

with open ("my_notes.txt" , "r" ) as file :

content = file .read ()

Python File Handling — Revision Notes Page 6


print (content )

# Output:

# Line one

# Line two

Example 4 — readlines() and Numbered Output

readlines_enumerate.py

with open ("my_notes.txt" , "r" ) as file :

lines = file .readlines ()

# lines is now a list: ["Line one\n", "Line two\n"]

# enumerate() gives us both index (number) and item (line)

for no , line in enumerate (lines , 1 ) :

print (f"Line {no}: {[Link]()}" )

# Output:

# Line 1: Line one

# Line 2: Line two

■■ Remember
readlines() keeps the \n at the end of each line. Always use .strip() when printing to remove that trailing newline.

Python File Handling — Revision Notes Page 7


Example 5 — Append to a File

append_file.py

# "a" mode adds to the END — existing content is SAFE

with open ("[Link]" , "a" ) as file :

file .write ("Day 4: Built my first project\n" )

# Old lines (Day 1, 2, 3) are still there + Day 4 added below

Example 6 — writelines() with a List

writelines_example.py

# writelines() writes a list of strings — NO auto newline!

info = [

"Day 1: Started learning Python\n" ,

"Day 2: Learned about files\n" ,

"Day 3: Feeling confident\n" ,

with open ("[Link]" , "w" ) as file :

file .writelines (info )

# Each string MUST include \n yourself

Example 7 — try/except for Safe File Reading

safe_read.py

try :

with open ("[Link]" , "r" ) as file :

content = file .read ()

print (content )

except FileNotFoundError :

print ("Sorry! That file does not exist." )

# Instead of crashing, the program shows a friendly message

Python File Handling — Revision Notes Page 8


■ Tip
Always wrap file-reading code in try/except when the file might not exist. Never assume a file is present — users
delete files all the time!

Example 8 — Search a File with Flag Variable

search_flag.py

name = input ("Enter name to search: " )

try :

with open ("[Link]" , "r" ) as file :

contacts = file .readlines ()

found = False # assume not found yet

for line in contacts :

if name .lower () in line .lower () : # case - insensitive

print (f"Found: {[Link]()}" )

found = True

break # stop after first match

if not found :

print ("Contact not found." )

except FileNotFoundError :

print ("Contact book is empty." )

# "found" flag tracks result — we only print "not found"

# AFTER checking ALL lines, not after each one

Python File Handling — Revision Notes Page 9


05 — Mini Project: Student Grade Book
A complete menu-driven program built using everything learned. Study this code carefully — it combines
functions, file modes, error handling, loops, flags, and user input all in one place.

Feature Overview

Function File Technique What it does

add_student() "a" mode — append Adds a student without losing existing data

view_students() "r" mode — readlines Prints all students with line numbers

search_student() "r" mode + flag Finds a student by name (case-insensitive)

Menu loop while True + int(input) Keeps running until user picks Exit

Part A — add_student() Function

[Link] [Part A]

def add_student () :

name = input ("Enter student's name: " )

try :

grade = int (input (f"Enter {name}'s grade: " ) )

except ValueError :

print ("Grade must be a number!" )

return # exit function early if bad input

with open ("[Link]" , "a" ) as file :

file .write (f"{name} - {grade}\n" ) # append , never overwrite

print (f"{name} added successfully!" )

Part B — view_students() Function

[Link] [Part B]

def view_students () :

try :

with open ("[Link]" , "r" ) as file :

contents = file .readlines ()

if not contents : # handle empty file

print ("Gradebook is empty." )

return

Python File Handling — Revision Notes Page 10


for no , line in enumerate (contents , 1 ) :

print (f"{no}. {[Link]()}" ) # strip removes \ n

except FileNotFoundError :

print ("Gradebook doesn't exist yet." )

Python File Handling — Revision Notes Page 11


Part C — search_student() Function

[Link] [Part C]

def search_student () :

name = input ("Which student's grade do you want: " )

try :

with open ("[Link]" , "r" ) as file :

contents = file .readlines ()

found = False # flag : default = not found

for content in contents :

if name .lower () in content .lower () : # case - insensitive


search

print (f"Found: {[Link]()}" )

found = True

break # stop as soon as we find the student

if not found :

print ("No record found." )

except FileNotFoundError :

print ("Gradebook doesn't exist yet." )

Part D — Main Menu Loop

[Link] [Part D — Main]

while True :

print (f"\n{'='*5} Grade Book {'='*5}" )

print ("1. Add Student" )

print ("2. View All Students" )

print ("3. Search Student" )

print ("4. Exit" )

try :

choice = int (input ("Choose an option: " ) )

except ValueError :

print ("Please enter a valid number!" )

continue # go back to top of loop

Python File Handling — Revision Notes Page 12


if choice = = 1 :

add_student ()

elif choice = = 2 :

view_students ()

elif choice = = 3 :

search_student ()

elif choice = = 4 :

print ("Goodbye!" )

break # exits the while loop

else :

print ("Enter a valid option (1-4)" )

■ break vs continue
continue — when the user types "abc" instead of a number, we catch the ValueError and use continue to jump
back to the top of the while loop and show the menu again.
break — when the user picks 4 (Exit), break exits the while True loop completely.

Python File Handling — Revision Notes Page 13


06 — Mistakes I Made
These are the actual mistakes made during this session. Understanding why something is wrong is more
important than just memorising the fix.

Mistake 1 — Wrong Loop Unpacking with Two Sequences

■ What went wrong


Tried to use content, range(1,5) in a for loop to iterate two things at once. Python does not work like that — a
single for loop iterates ONE sequence.

mistake_1_wrong.py ← DO NOT USE

# WRONG: Python sees (content, range(1,5)) as a TUPLE

# The loop runs only 2 times — once for the list, once for the range

for line , no in content , range (1 , 5 ) :

print (f"Line {no}: {line}" )

mistake_1_correct.py ✓

# CORRECT: enumerate() pairs each item with a number automatically

for no , line in enumerate (content , 1 ) :

print (f"Line {no}: {[Link]()}" )

Mistake 2 — Printing \n (blank line) with readlines() Output

■ What went wrong


readlines() keeps the \n at the end of every line. Without .strip(), printing creates a double-spaced output (one
from \n, one from print's own newline).

mistake_2_wrong.py ← DO NOT USE

# WRONG: "no" still has \n at the end → extra blank line in output

print (f"Found: {no}" )

mistake_2_correct.py ✓

# CORRECT: .strip() removes the trailing \n cleanly

print (f"Found: {[Link]()}" )

Python File Handling — Revision Notes Page 14


Mistake 3 — Printing 'not found' After Every Non-Matching Line

■ What went wrong


Placed the "not found" message inside the else of the for loop. This printed "Contact not found." for EVERY line
that did not match — not just once at the end.

mistake_3_wrong.py ← DO NOT USE

for line in contacts :

if name in line :

print (f"Found: {line}" )

else :

# This runs for EVERY non-matching line — not just once!

print ("Contact not found." )

mistake_3_correct.py ✓

found = False # set flag before the loop

for line in contacts :

if name in line :

print (f"Found: {[Link]()}" )

found = True

break # stop immediately

# Only checked ONCE, after the entire loop

if not found :

print ("Contact not found." )

Mistake 4 — Using Capital Letter for a Variable Name (Found)

■ What went wrong


Used Found = False (capital F). In Python, CapitalCase names are reserved for class definitions (like MyClass).
Variable names should always use lowercase or snake_case.

mistake_4_wrong.py ← style error

Found = False # Looks like a Class name — confuses other developers

mistake_4_correct.py ✓

found = False # lowercase snake_case for variables — Python convention

Python File Handling — Revision Notes Page 15


■■ Why it Matters
This does NOT crash your code, but it confuses anyone reading it — including yourself later. Always follow
naming conventions. Python's official guide is called PEP 8.

Python File Handling — Revision Notes Page 16


07 — Things to Remember

01 Always use with open() — it closes the file automatically, even if an error occurs inside the block.

02 "w" destroys existing content — if you need to add without erasing, use "a" (append).

readlines() keeps \n at the end of every line. Use .strip() whenever you print lines from
03 readlines().

04 writelines() does NOT add \n — you must include "\n" manually inside each string in your list.

Use a flag variable (found = False) when searching a file. Only print "not found" once — after the
05 complete loop, not inside it.

enumerate(list, 1) is the correct way to loop with both a number and an item. The order is: for
06 number, item.

Wrap file reading in try/except FileNotFoundError — never assume a file exists. Users
07 rename or delete files.

Wrap int(input()) in try/except ValueError — users sometimes type letters when you expect a
08 number. Use continue to re-show the menu.

Use .lower() on both sides of a string comparison for case-insensitive search: [Link]()
09 in [Link]()

Variable names use lowercase_snake_case. Only class names use CapitalCase. This is PEP 8 —
10 Python's official style guide.

■ Topic Complete — Python: Reading & Writing Files

Python File Handling — Revision Notes Page 17

You might also like