File Handling — Creation, Writing, Appending
Creating and Writing a File — mode 'w'
'w' mode creates a new file if it does not exist, and overwrites it completely if it does.
with open("diary.txt", "w") as f:
f.write("Day 1: Learned Python basics.\n")
f.write("Day 2: Practiced control structures.\n")
writelines() — write multiple lines from a list
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w") as f:
f.writelines(lines)
Reading a File
with open("diary.txt", "r") as f:
content = f.read() # reads the ENTIRE file as one string
print(content)
with open("diary.txt", "r") as f:
for line in f: # reads line by line (memory efficient)
print(line.strip())
with open("diary.txt", "r") as f:
lines = f.readlines() # returns a LIST of lines
print(lines)
Appending to a File — mode 'a'
'a' mode adds content to the end of an existing file without erasing prior content. If the file doesn't exist, it is created.
with open("diary.txt", "a") as f:
f.write("Day 3: Learned about file handling.\n")
with open("diary.txt", "r") as f:
print(f.read())
# Day 1: Learned Python basics.
# Day 2: Practiced control structures.
# Day 3: Learned about file handling.
'w' vs 'a' — critical distinction
with open("test.txt", "w") as f:
f.write("First write")
with open("test.txt", "w") as f: # 'w' OVERWRITES -- "First write" is lost
f.write("Second write")
print(open("test.txt").read()) # "Second write" only
with open("test.txt", "a") as f: # 'a' APPENDS -- keeps existing content
f.write(" + appended text")
print(open("test.txt").read()) # "Second write + appended text"
Writing numbers to a file (must convert to string)
marks = [85, 90, 78]
with open("marks.txt", "w") as f:
for m in marks:
f.write(str(m) + "\n") # write() requires a string, not int