Lesson 106 min read
File I/O
Read and write files — because your data deserves to outlive your program
Opening Files — The with Statement
Reading a file in Python is like checking out a library book: you open it, read it, and then close it when you're done. If you forget to close it, bad things can happen (corrupted data, locked files, resource leaks).
The with statement is your best friend here — it automatically closes the file when you're done, even if an error occurs. Always use it.
The open() function takes a filename and a mode:
"r"— Read (default). File must exist."w"— Write. Creates file or overwrites existing content!"a"— Append. Adds to the end without erasing."x"— Exclusive create. Fails if the file already exists.- Add
"b"for binary mode:"rb","wb".
Writing & Reading Files
Reading Methods Compared
Python gives you three ways to read file contents:
.read()— Returns the entire file as one big string. Great for small files..readline()— Returns one line at a time. Call it again for the next line..readlines()— Returns a list of all lines. Each line includes the\nnewline character.- Iterating the file object — The best way for large files. Reads one line at a time without loading the whole thing into memory.
Appending & Using readlines()
Working with CSV Files
CSV (Comma-Separated Values) is one of the most common file formats for data. Python has a built-in csv module, but for simple cases you can handle it with just .split() and f-strings.
CSV Basics
Note: Always use the
with statement when working with files. It's like having a responsible roommate who always turns off the lights when leaving — your files get properly closed even if your code crashes halfway through.