The three ways to read a file in Python
Python gives you three main ways to read a file: read() loads the entire file into memory at once, readline() pulls one line at a time, and readlines() loads all lines into a list. Which one you use depends on how large your file is and what you plan to do with the data.
Before you can read anything, you need to open the file using the open() function. This creates a file object that Python can work with. The basic structure looks like this: open("filename.txt", "r"). The "r" tells Python you want to read the file, not write to it.
The safest way to work with files is to use a with statement. This automatically closes the file when you are done, even if something goes wrong. Without it, you have to remember to close the file yourself, and forgetting causes problems.
Key Takeaways
- Always use a with statement when opening files so Python closes them automatically when you finish.
- Use read() for small files you want to work with all at once, readline() for one line at a time, and readlines() to get all lines as a list.
- The file path can be relative (pointing to a file in your project folder) or absolute (the full path from your computer's root).
- If Python cannot find your file, check that the filename and path are spelled correctly and that the file actually exists in that location.
Reading an entire file at once with read()
The read() method pulls the whole file into a single string. This works well for small files or when you need to process the entire content as one block. Here is the basic pattern:
Open your text editor and type this:
- with open("myfile.txt", "r") as file:
- content = file.read()
- print(content)
When you run this code, Python opens myfile.txt, reads everything in it, stores it in the variable content, and prints it. The indentation matters — everything inside the with block must be indented.
The downside of read() is that it loads the entire file into memory. If your file is gigabytes in size, this will slow your computer down or crash it. For large files, use readline() or readlines() instead.
Reading one line at a time with readline()
The readline() method reads a single line from the file each time you call it. This is useful for large files because you only keep one line in memory at a time. Here is how to use it:
- with open("myfile.txt", "r") as file:
- line1 = file.readline()
- line2 = file.readline()
- print(line1)
- print(line2)
Each call to readline() moves forward in the file. The first call gets line 1, the second call gets line 2, and so on. When you reach the end of the file, readline() returns an empty string.
In practice, you usually pair readline() with a loop so you do not have to call it manually for every line. A while loop works well here: keep reading lines until you get an empty string, which signals the end of the file.
Reading all lines into a list with readlines()
The readlines() method reads the entire file and returns a list where each item is one line. This is the middle ground between read() and readline() — you get all the lines, but as separate items you can loop through:
- with open("myfile.txt", "r") as file:
- lines = file.readlines()
- for line in lines:
- print(line)
Each line in the list includes the newline character at the end (\n). If you want to remove it, use the strip() method: line.strip() removes whitespace from both ends of the string.
The readlines() approach is cleaner than calling readline() repeatedly, but it still loads the whole file into memory. For very large files, use a for loop directly on the file object instead, which reads one line at a time without storing them all.
Looping through a file line by line
The most efficient way to read a large file is to loop directly over the file object. Python reads one line at a time and discards it after you process it, so memory usage stays low:
- with open("myfile.txt", "r") as file:
- for line in file:
- print(line.strip())
This pattern is faster and uses less memory than readlines() because Python does not store all lines at once. It reads the next line only when the loop asks for it. This is the approach to use for log files, large datasets, or any file you do not need to keep entirely in memory.
The strip() method removes the newline character and any extra spaces at the start or end of each line. Without it, print() adds an extra blank line after each line from the file.
Handling file paths and common errors
Python looks for files in the current working directory by default. If your file is in a different folder, you need to give Python the correct path. A relative path points to a file from your current location: open("data/myfile.txt", "r") looks for myfile.txt inside a folder called data. An absolute path starts from your computer's root: open("/Users/yourname/Documents/myfile.txt", "r") on Mac or open("C:\\Users\\yourname\\Documents\\myfile.txt", "r") on Windows.
The most common error is FileNotFoundError, which means Python cannot find the file. Check three things: the filename is spelled correctly, the path is correct, and the file actually exists in that location. On Windows, use backslashes or forward slashes in paths — both work in Python.
If you want to handle the error gracefully instead of crashing, wrap your code in a try and except block. This lets you catch the error and do something else, like print a message telling the user the file was not found.
Reading specific file types
Text files work with the methods above, but other file types need different approaches. For CSV files (spreadsheet data), use the csv module that comes with Python. For JSON files (structured data), use the json module. For Excel files, you need to install a third-party module like openpyxl.
These modules handle the structure of the file format for you. For example, the csv module automatically splits each line into columns, so you do not have to parse it yourself. If you are working with anything other than plain text, look up the module for that file type — it will save you time and prevent bugs.
For now, focus on reading plain text files with the methods above. Once you are comfortable with those, exploring specialized modules becomes much easier.
Frequently Asked Questions
What is the difference between read(), readline(), and readlines()?
read() loads the entire file as one string. readline() reads one line each time you call it. readlines() reads all lines and returns them as a list. For large files, loop directly over the file object instead — it reads one line at a time without storing them all in memory.
Do I have to use a with statement?
No, but you should. Without with, you must call file.close() yourself when you finish. If your code crashes before you close it, the file stays open and can cause problems. The with statement closes the file automatically, even if an error occurs.
How do I read a file from a different folder?
Use a relative path like open("data/myfile.txt", "r") if the file is in a subfolder, or open("../myfile.txt", "r") to go up one folder. On Windows, backslashes work: open("data\\myfile.txt", "r"). Forward slashes work on all systems, including Windows.
What does FileNotFoundError mean?
Python cannot find the file at the path you gave it. Check that the filename is spelled correctly, the path is right, and the file exists. Use print() to verify the path Python is looking for, or use a file manager to confirm the file is where you think it is.
Can I read a file while another program is using it?
Yes, you can read a file while another program has it open. Python opens the file in read mode, which does not lock it. However, if another program is actively writing to the file while you read it, you might get incomplete or corrupted data. Wait for the other program to finish if you need the complete file.