The Basic Way to Read a Text File
The simplest way to read a text file in Python is to use the open() function with the read() method. This loads the entire file into memory as a single string. Here's what that looks like:
Open the file with open("filename.txt", "r"), where "r" means read mode. Then call .read() on the file object to get all the text at once. When you're done, close the file with .close() to free up system resources. In practice, this means three lines of code: open, read, close.
For small files this works fine. For large files — anything over a few megabytes — loading everything into memory at once can slow your program down. That's when you switch to one of the other methods below.
Key Takeaways
- The open() function with .read() loads an entire file into memory as one string, which works for small files but wastes memory on large ones.
- The .readline() method reads one line at a time, and .readlines() returns a list of all lines, each as a separate item.
- A for loop over an open file object reads one line per loop without storing the whole file in memory, which is the most efficient method for large files.
- Always close a file after reading it, or use a with statement to close it automatically when the block ends.
- The "r" mode reads text as strings; use "rb" to read binary files or "r" with encoding specified if the file uses a non-standard character set.
Reading One Line at a Time
If you want to process a file line by line instead of all at once, use .readline() to read a single line, or .readlines() to get a list where each item is one line. The .readline() method is useful when you need to stop partway through a file or when you're working with a file so large that even one line at a time matters.
The .readlines() method returns a list of strings, one per line, with the newline character (\n) still attached to each line. This is helpful if you want to loop through lines and keep them in order, but it still loads the whole file into memory like .read() does.
Both methods include the newline character at the end of each line. If you want clean text without the \n, use .strip() on each line after reading it.
Looping Through a File Without Loading It All at Once
The most memory-efficient way to read a large file is to loop directly over the file object with a for loop. Python reads one line at a time and discards it after your loop processes it, so the entire file never sits in memory.
This approach looks like: open the file, then write for line in file_object: and indent your code underneath. Each time the loop runs, line holds one line from the file. When the loop ends, move to the next line automatically. This is the standard way to handle files with thousands or millions of lines.
The newline character is still present at the end of each line, so strip it if you need clean text. This method is faster and uses far less memory than .read() or .readlines() on large files.
Using the with Statement to Close Files Automatically
Forgetting to close a file can cause problems — the file stays locked in memory, and if your program crashes before reaching .close(), the file never closes at all. The with statement solves this by closing the file automatically when the block ends, even if an error occurs.
The syntax is with open("filename.txt", "r") as file_object: followed by indented code. Everything inside the indented block can use file_object. When the block ends, Python closes the file without you having to write .close(). This is the recommended way to read files in modern Python code.
Using with is especially important in programs that read many files or run for a long time, because each unclosed file uses system resources that eventually run out.
Handling Different File Encodings
Most text files use UTF-8 encoding, which Python assumes by default. But some files use other encodings like ASCII, Latin-1, or Windows-1252. If you try to read a file with the wrong encoding, you'll get an error or see garbled characters.
To specify an encoding, add encoding="utf-8" (or whatever encoding the file uses) to the open() function. For example: open("filename.txt", "r", encoding="latin-1"). If you're not sure what encoding a file uses, UTF-8 is the safest guess for modern files. Older Windows files often use "cp1252" or "latin-1".
If you still get an error, you can tell Python to ignore or replace unreadable characters by adding errors="ignore" or errors="replace" to the open() function. This lets the file read without crashing, though some text may be lost or replaced with a placeholder character.
Reading Binary Files and Handling Special Cases
Text files contain human-readable characters. Binary files contain raw data like images, audio, or compiled programs. To read a binary file, use "rb" mode instead of "r". Binary mode returns bytes instead of strings, so you work with raw data rather than text.
If you need only part of a file, use .seek() to jump to a specific position and .tell() to find out where you are. For example, file_object.seek(100) moves to byte 100, and the next read starts from there. This is useful for very large files where you only need a section in the middle.
For structured data like CSV or JSON files, don't read them as plain text. Python has built-in modules — csv and json — that parse these formats automatically and return organized data instead of raw strings.
Common Mistakes and How to Avoid Them
The most common mistake is forgetting to close the file or not using with, which leaves files locked in memory. Always use with unless you have a specific reason not to. Another mistake is assuming the file exists — if you try to open a file that isn't there, Python raises a FileNotFoundError. Wrap open() in a try/except block if the file might not exist.
A third mistake is forgetting that .read() returns the entire file as one string, not a list of lines. If you loop over the result of .read(), you loop over individual characters, not lines. Use .readlines() or loop over the file object directly if you want to process line by line.
Finally, don't assume the file uses UTF-8 encoding without checking. If you get garbled text or an encoding error, try specifying the encoding explicitly in the open() function.
Frequently Asked Questions
What's the difference between .read(), .readline(), and .readlines()?
.read() returns the entire file as one string. .readline() returns one line as a string. .readlines() returns a list of all lines, where each item is one line. Use .read() for small files you want to process all at once, .readline() when you need to stop partway through, and .readlines() when you want all lines in a list but still need them in memory.
Should I always use the with statement?
Yes. The with statement closes the file automatically when the block ends, even if an error occurs. This prevents files from staying locked in memory and is the standard practice in Python. The only exception is in interactive code where you're experimenting, but even then it's a good habit.
How do I read only part of a file?
Use .seek() to jump to a specific byte position, then read from there. For example, file_object.seek(1000) moves to byte 1000, and the next .read() starts from that point. For line-based reading, use a for loop and break out when you've read enough lines.
What does the "r" in open("file.txt", "r") mean?
The "r" means read mode — you can only read the file, not write to it. Other modes include "w" for write (overwrites the file), "a" for append (adds to the end), and "rb" for binary read. Always use "r" unless you specifically need to change the file.
Why do I get an encoding error when reading a file?
The file uses a different encoding than Python expects. By default, Python assumes UTF-8. If the file uses Latin-1, Windows-1252, or another encoding, specify it with encoding="encoding-name" in the open() function. If you don't know the encoding, try UTF-8 first, then Latin-1 if that fails.