How to Read and Write CSV, JSON and Text Files in Python (with open and with)
P9.2 How to Read and Write Text Files in Python
Why. Logs, notes and simple lists are plain text. Reading them is the first file skill.
What. open(path, mode) opens a file. Modes: "r" read, "w" write (replaces the file), "a" append. The with statement closes the file automatically.
How.
Write then read a text file
- Open with
with open("file.txt", "w", encoding="utf-8") as f:. - Write with
f.write("text\n"). - Open again with
"r". - Read all with
f.read()or line by line with a for loop.
Worked example A — Write a small log.
Step 1 — What we do. A support desk in Bengaluru logs three tickets.
Step 2 — Type and run this code.
with open("tickets.txt", "w", encoding="utf-8") as f:
f.write("T1 login issue\n")
f.write("T2 refund request\n")
f.write("T3 address change\n")
print("Saved")
Step 3 — Output you should see.
Saved
Step 4 — What it means. The file is created (or replaced). \n starts a new line.
Worked example B — Read it back line by line.
Step 1 — What we do. We read the same log and count lines.
Step 2 — Type and run this code.
with open("tickets.txt", "w", encoding="utf-8") as f:
f.write("T1 login issue\nT2 refund request\nT3 address change\n")
count = 0
with open("tickets.txt", encoding="utf-8") as f:
for line in f:
count += 1
print(line.strip())
print("Lines:", count)
Step 3 — Output you should see.
T1 login issue
T2 refund request
T3 address change
Lines: 3
Step 4 — What it means. Each line includes \n at the end, so .strip() removes it.
Worked example C — Append a new line.
Step 1 — What we do. A new ticket arrives. "a" adds to the end instead of replacing.
Step 2 — Type and run this code.
with open("tickets.txt", "w", encoding="utf-8") as f:
f.write("T1 login issue\n")
with open("tickets.txt", "a", encoding="utf-8") as f:
f.write("T4 card blocked\n")
print(open("tickets.txt", encoding="utf-8").read())
Step 3 — Output you should see.
T1 login issue
T4 card blocked
Step 4 — What it means. "w" would have wiped T1. Use "a" to keep old lines.
Ravindra Bagale's Tip
Always pass encoding="utf-8". It keeps ₹, €, £ and Marathi/Hindi text safe on every computer.
Ravindra Bagale's Tip – मराठी
नेहमी encoding="utf-8" द्या. त्यामुळे ₹, €, £ आणि मराठी/हिंदी text प्रत्येक computer वर सुरक्षित राहतो.
Ravindra Bagale's Tip – हिंदी
हमेशा encoding="utf-8" दो. इससे ₹, €, £ और मराठी/हिंदी text हर computer पर सुरक्षित रहता है.