Working with Files
Working with Files
Reading and Writing Text
Programs often need to save data between runs or load data produced elsewhere. Python's built-in file handling is simple: open a file, read or write, and close it. The modern way is the with statement, which closes the file automatically even if an error occurs.
with open("notes.txt", "w") as f:
f.write("Hello from Python
")
f.write("Second line
")
The second argument is the mode. "w" creates the file and truncates anything already there, "a" appends to the end, and "r" opens for reading. If you open a missing file in "r" mode, Python raises a FileNotFoundError, which you will learn to handle in the next post.
Reading Files Back
Reading is just as direct. The read method returns the whole file as one string, readline returns a single line, and readlines returns a list of lines. Because the with block manages the resource, you stay safe from leaving files open.
with open("notes.txt", "r") as f:
for line in f:
print(line.strip())
Looping over the file object line by line is efficient even for very large files, because Python does not load the entire file into memory at once.
Character Encoding
Text files store characters using an encoding, and UTF-8 is the modern default. When you open a file with unusual characters, pass encoding="utf-8" to avoid garbled text on other systems. Writing files with the default settings on a laptop and reading them on a server can differ, so being explicit about encoding prevents surprises.
Handling Paths
The pathlib module makes location-independent path handling easy. It builds paths with the correct separator for your operating system, which is crucial when code runs on both Windows and Linux.
from pathlib import Path
folder = Path("data")
folder.mkdir(exist_ok=True)
file_path = folder / "log.txt"
print(file_path) # data/log.txt
The slash operator joins path pieces cleanly, and methods like .read_text() and .write_text() combine opening and reading into one call.
Key Points
- Use with open(...) to manage files safely and automatically.
- Modes are "r" for read, "w" for write, and "a" for append.
- Loop over the file object to process large files line by line.
- Pass encoding="utf-8" for reliable text handling.
- Use pathlib for clean, cross-platform path operations.