Pythonintermediate 8 min
Read and write text files safely with open and the with statement.
How to write text to a file, read it back, append to it, and why to use with open(...).
Programs need to save things: notes, logs, settings, results. Files are the simplest way to keep data after the program ends.
You open a file with open(path, mode). The mode says what you want:
"r": read (the default). The file must exist."w": write. Creates the file, or erases an existing one."a": append. Adds to the end.Always open files with with. It closes the file for you, even if an error happens:
Ways to read: f.read() gives the whole text, f.readlines() gives a list of lines, and looping for line in f: goes one line at a time.
line.strip() removes the newline at the end. Add encoding="utf-8" to avoid surprises with non-English text.
"w" creates todo.txt and writes two lines."a" adds a third line without erasing the first two."r" reads the file. The comprehension strips the newline from each line.['Buy milk', 'Call Ravi', 'Study Python'], with 3 tasks.enumerate(lines, start=1) numbers them: 1 Buy milk, 2 Call Ravi, 3 Study Python.Append a fourth task and print the number of lines again.
"w" when you meant "a", erasing the file.\n, so everything ends up on one line.with.FileNotFoundError.open(path, mode) with modes r, w, a.with so files are closed.read() and readlines().Next: organising code with classes.
with open("notes.txt", "w") as f:
f.write("Hello\n")with open("todo.txt", "w", encoding="utf-8") as f:
f.write("Buy milk\n")
f.write("Call Ravi\n")
with open("todo.txt", "a", encoding="utf-8") as f:
f.write("Study Python\n")
with open("todo.txt", "r", encoding="utf-8") as f:
lines = [line.strip() for line in f]
print(lines)
print("Tasks:", len(lines))
for i, task in enumerate(lines, start=1):
print(i, task)