Python Files & Errors
Python Read and Write Files
Once a file is open, Python gives you several methods to pull data out of it or push data into it. This lesson covers the core read and write methods you will use constantly.
Reading a Whole File
The read() method returns the entire file content as one string. It is simple, but for large files it can use a lot of memory since everything loads at once.
f = open("notes.txt", "r")
text = f.read()
print(text)
f.close()Reading Line by Line
readline() returns just one line each time you call it, including the trailing newline character. readlines() returns every line at once as a list of strings, which pairs nicely with a for loop.
f = open("notes.txt", "r")
first_line = f.readline()
print(first_line)
f.close()
f = open("notes.txt", "r")
lines = f.readlines()
print(lines) # ['Hello\n', 'World\n']
f.close()The most Pythonic way to process a file, especially a large one, is to loop directly over the file object. Python reads it lazily, one line at a time, which is fast and memory-efficient.
f = open("students.txt", "r")
for line in f:
print(line.strip())
f.close()Use .strip() on each line to remove the trailing \n newline character before printing or storing it.
Writing to a File
write() sends one string to the file, and writelines() sends a list of strings in one go. Neither method adds newlines automatically, so include \n yourself where needed.
f = open("output.txt", "w")
f.write("Line one\n")
f.write("Line two\n")
f.close()
lines = ["Apple\n", "Banana\n", "Cherry\n"]
f = open("fruits.txt", "w")
f.writelines(lines)
f.close()Appending Instead of Overwriting
Open the file in "a" mode to add new content at the end without touching what is already there — perfect for logs or growing a data file over time.
f = open("fruits.txt", "a")
f.write("Mango\n")
f.close()| Method | Returns | Best for |
|---|---|---|
| read() | Whole file as one string | Small files |
| readline() | One line per call | Reading a header, then the rest |
| readlines() | List of all lines | When you need list operations like len() |
| for line in file | One line per loop step | Large files, memory efficient |
| write(text) | Writes one string | Single writes |
| writelines(list) | Writes many strings | Writing a list of strings at once |
