Python Reading Files
Table of Contents + β
In the last lesson you learned about Custom Exceptions. There you made your own error types for when something goes wrong. Now we step outside the program itself. So far every value lived inside your code, or it came from someone typing. But a lot of the data you care about already sits in files on the disk. Notes. Settings. Lists. Logs. This lesson shows you how to open one of those files and read what is inside.
π€ Why Read Files?
Think about it for a second. A program that forgets everything the moment it stops is not much use. You write a shopping list. You close the app. It is gone. That is the pain. Anything typed into input() disappears when the program ends.
A file fixes that. A file is just a piece of data saved on the disk. It stays there after your program stops. So if you save some names to a file today, you can read them back tomorrow.
The way in is one function. open() hands you a connection to a file. Once that file is open, you can read every line inside it.
π Opening a File First
Before you can read anything, you have to open the file. That is what open() is for.
Here is the simplest form. It opens a file called notes.txt.
file = open("notes.txt", "r")Two things go inside the brackets.
- The first part,
"notes.txt", is the file name. It is the file you want to open. - The second part,
"r", is the mode. The mode tells Python what you plan to do with the file. The letter"r"means βreadβ. So you are only looking, not changing anything.
You can read that line out loud as βopen notes.txt so I can read it.β The open() call gives back a file object. We stored it in file. That object is your handle to the file. You use it to actually pull the text out.
Note
For these examples, imagine a file named notes.txt sitting next to your Python file. It has these three lines inside it:
Buy milkCall AlexFinish the reportπ Reading the Whole File With read()
The most direct way is read(). It pulls in the entire file as one big string.
This code opens the file, reads all of it into a variable, and prints it.
file = open("notes.txt", "r")content = file.read()print(content)file.close()Letβs walk through it line by line.
open("notes.txt", "r")opens the file for reading.file.read()grabs everything in the file as a single string and stores it incontent.print(content)shows that string.file.close()closes the file when we are done. More on that closing step soon.
Output
Buy milkCall AlexFinish the reportread() is handy when the file is small and you want the whole thing at once. The line breaks you see come from the file itself. Each line in the file ends with a hidden newline character. print shows them as separate lines.
π Reading One Line With readline()
Sometimes you do not want the whole file. You just want the next line. That is what readline() does. It reads a single line and then stops.
This code reads the first two lines, one at a time.
file = open("notes.txt", "r")first = file.readline()second = file.readline()print(first)print(second)file.close()Each call to readline() picks up where the last one left off. The first call grabs "Buy milk". The second call grabs the next line, "Call Alex". The file remembers its position for you.
Output
Buy milk
Call AlexSee the extra blank lines? Each line you read from the file still has its newline on the end. Then print adds its own newline on top. So you get two. You can remove the fileβs newline with .strip() if those gaps bother you. Once you apply .strip(), the blank lines go away. We will do exactly that in the looping example coming up.
π Reading All Lines Into a List With readlines()
What if you want every line, but kept as separate items you can loop over or count? That is the job of readlines(). Notice the s on the end. It reads the whole file and gives you back a list, with one line per item.
This code reads the file into a list and prints that list.
file = open("notes.txt", "r")lines = file.readlines()print(lines)file.close()Now lines is a normal Python list. Each item is one line from the file, with its newline still attached.
Output
['Buy milk\n', 'Call Alex\n', 'Finish the report\n']Those \n bits at the end of each item are the newline characters. They are how the file marks where one line ends and the next begins. Because lines is a real list, you can do list things with it. For example, you can check how many lines there are with len(lines).
π Looping Line by Line (the Common Way)
Here is the one you will reach for most. You can loop over the file object directly with a for loop. Python hands you one line each time around.
This code goes through the file line by line and prints each one, cleaned up.
file = open("notes.txt", "r")for line in file: print(line.strip())file.close()Read it like this.
for line in file:walks through the file one line at a time.- Each time around,
lineholds the next line of the file. line.strip()removes the newline on the end, plus any spare spaces. So the output stays tidy.
Output
Buy milkCall AlexFinish the reportWhy is this the common way? It reads only one line at a time. It does not load the whole file into memory at once. So even a huge file stays light on memory. For most real work, looping over the file like this is the right choice.
Tip
Use .strip() on each line to drop the trailing newline. It is the small habit that keeps your printed output free of those extra blank gaps.
π§Ή You Must Close the File
You may have noticed file.close() at the end of every example. That matters.
When you open a file, your program holds onto it. The system keeps that connection open until you let go. So you should always close the file when you are done with it.
Here is the pain if you forget.
- The file connection stays open. That wastes system resources.
- On some systems, other programs cannot use the file properly until you close it.
- Open one file in a long loop without closing, and you can run out of open file slots.
# β Avoid: opening and never closingfile = open("notes.txt", "r")content = file.read()print(content)# the file is left open
# β
Good: close it when you are donefile = open("notes.txt", "r")content = file.read()print(content)file.close()The trouble is that it is easy to forget close(). And if an error happens before that line, the close never runs at all. Python has a cleaner way to handle this. It is called a context manager, and you use it with the with keyword. It closes the file for you automatically. That is the very next lesson. So for now just remember the rule. If you open it, close it.
π The Ways to Read at a Glance
Keep this small table near you while the four methods settle in.
| Method | What you get back | Good for |
|---|---|---|
read() | The whole file as one string | Small files you want all at once |
readline() | The next single line as a string | Reading one line at a time |
readlines() | A list of all lines | When you need a list to loop or count |
for line in file | One line each time around | Most cases, even large files |
β οΈ Common Mistakes
A few traps catch people again and again. Watch for these.
- Opening a file that is not there. If the file name is wrong, or the file does not exist, Python stops with a
FileNotFoundError.
# β Avoid: this crashes if the file is missingfile = open("notessss.txt", "r")Output
Traceback (most recent call last): File "main.py", line 1, in <module> file = open("notessss.txt", "r")FileNotFoundError: [Errno 2] No such file or directory: 'notessss.txt'-
Forgetting to close the file. The connection stays open and wastes resources. Always call
file.close()when you finish. -
Reading the same file object twice and getting nothing the second time. Once you read to the end, the position sits at the end. So a second
read()returns an empty string.
# β Avoid: the second read gives back nothingfile = open("notes.txt", "r")print(file.read()) # prints the whole fileprint(file.read()) # prints an empty string, already at the endfile.close()- Forgetting to strip the newline. Then your printed output has extra blank gaps between lines.
β Best Practices
Keep these small habits and reading files stays easy.
- Always open with a clear mode. Write
"r"when you only want to read, so your intent is obvious. - Close every file you open with
file.close(). Or better, use thewithkeyword you will meet next. - For most files, loop with
for line in file. It is simple and it stays light on memory. - Use
.strip()on each line to drop the trailing newline before you print or compare it. - Reach for
read()only when the file is small enough to hold all at once.
π§© What Youβve Learned
You can now open a text file and pull the words out of it. Here is the short version.
- β
open(filename, "r")opens a file in read mode, where"r"means βread onlyβ. - β
read()returns the whole file as one string, good for small files. - β
readline()returns the next single line, and the file remembers its position. - β
readlines()returns a list with one line per item, newlines included. - β
Looping with
for line in filereads one line at a time and works even on big files. - β
Always close the file with
file.close()when you are done.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
What does the "r" mean in open("notes.txt", "r")?
Why: The "r" mode opens the file for reading only, so you can look at its contents but not change them.
- 2
Which method reads the whole file and returns it as one single string?
Why: read() pulls the entire file in as one string, which is handy for small files you want all at once.
- 3
What does readlines() give you back?
Why: readlines() returns a list where each item is one line from the file, with its newline still attached.
- 4
Why should you call file.close() when you finish reading?
Why: Closing the file releases the connection your program was holding, which frees system resources.
π Whatβs Next?
You can read what is already in a file. Now letβs go the other way. We will put your own data into a file so it stays around after the program ends.