Pages

Python File Handling - Read & Write

 # Goal: Save and load data from files

# Topics:
# • Opening files (open, with statement)
# • Reading files (read, readlines)
# • Writing files (write, writelines)
# • Working with text files

# ── 1. Writing a File (write) ─────────────────────────────────────────────────

with open("sample.txt", "w") as f: # opens for writing; creates if not exists
f.write("Hello, File!\n") # writes a single line
f.write("Python file handling.\n") # writes another line
f.write("Line 3 here.\n") # writes third line

print("File written.") # File written.

# ── 2. Reading Entire File (read) ─────────────────────────────────────────────

with open("sample.txt", "r") as f: # opens for reading
content = f.read() # reads entire file as one string

print(content)
# Hello, File!
# Python file handling.
# Line 3 here.

# ── 3. Reading Line by Line (readlines) ──────────────────────────────────────

with open("sample.txt", "r") as f:
lines = f.readlines() # returns a list of lines (with \n)

print(lines) # ['Hello, File!\n', 'Python file handling.\n', 'Line 3 here.\n']
print(f"Total lines: {len(lines)}") # Total lines: 3

for i, line in enumerate(lines, start=1):
print(f"Line {i}: {line.strip()}") # Line 1: Hello, File!
# Line 2: Python file handling.
# Line 3: Line 3 here.

# ── 4. Appending to a File (writelines) ──────────────────────────────────────

new_lines = ["Line 4 added.\n", "Line 5 added.\n"]

with open("sample.txt", "a") as f: # "a" = append; does not overwrite
f.writelines(new_lines) # writes a list of strings at once

print("Lines appended.") # Lines appended.

# Verify append
with open("sample.txt", "r") as f:
for line in f: # iterate file object directly (memory efficient)
print(line.strip())
# Hello, File!
# Python file handling.
# Line 3 here.
# Line 4 added.
# Line 5 added.

# ── 5. Overwriting with writelines ───────────────────────────────────────────

data = ["Alice,30\n", "Bob,25\n", "Carol,28\n"]

with open("people.txt", "w") as f:
f.writelines(data) # writes list of strings in one call

print("people.txt written.") # people.txt written.

# Read back and display
with open("people.txt", "r") as f:
content = f.read()

print(content)
# Alice,30
# Bob,25
# Carol,28

# ── 6. Mini Project: Note Saver ──────────────────────────────────────────────

print("\n--- Note Saver ---")
notes = []
print("Enter notes (blank line to stop):")

while True:
note = input("> ")
if note == "":
break
notes.append(note + "\n")

with open("notes.txt", "w") as f:
f.writelines(notes) # saves all notes to file

print(f"\n{len(notes)} note(s) saved to notes.txt.") # e.g. 3 note(s) saved to notes.txt.

# Read and display saved notes
print("\n--- Saved Notes ---")
with open("notes.txt", "r") as f:
for i, line in enumerate(f, start=1):
print(f"{i}. {line.strip()}") # 1. <first note>
# 2. <second note>

No comments:

Post a Comment

Please comment below to feedback or ask questions.