Reading files
Part of the free LogicWiz Python course, Module 8: Files. The examples and practice run in the app.
Every evening Canteen Counter forgets everything. Close the tab and the whole day of sales is gone. Files are how a program remembers, and the first skill is reading one.
You'll learn to
- Open a file by its path, and always close it with `with`
- Choose between `read()`, `readline()` and `readlines()`
- Loop over the lines of a file and strip the hidden `\n`
Learn
Files and paths
A file is named text (or bytes) saved on disk, so it survives after the program ends. To open one, Python needs its path:
- Relative path:
"menu.txt"means "in the folder the program runs in"."data/menu.txt"means "in thedatafolder inside it". Use these almost always. - Absolute path: the full address from the top, like
"C:/Users/aarav/menu.txt"on Windows or"/home/meher/menu.txt"on Linux.
On Windows, write the path with forward slashes, or as a raw string r"C:\Users\aarav\menu.txt", because \n inside a normal string means a new line, not a folder.
open, read, close
f = open("menu.txt") # mode "r" (read) is the default
text = f.read()
f.close()
print(text)
print(len(text), "characters")
open() gives back a file object (also called a file handle). read() returns the whole file as one string, newlines included. The page put menu.txt in the program's folder for you.
with closes it for you
Forget f.close() and the file can stay locked, or what you wrote may never reach the disk. So Python has a safer form:
with open("menu.txt") as f:
text = f.read()
# here the file is already closed
The file is open only inside the indented block. When the block ends, even because of an error, Python closes it. Use with every time; it is what examiners and interviewers expect.
Three ways to read
| Call | What you get |
|---|---|
| f.read() | The whole file as one string |
| f.read(5) | The next 5 characters |
| f.readline() | The next line with its \n; "" (empty string) at the end of the file |
| f.readlines() | A list of all remaining lines, each ending in \n |
| for line in f: | One line at a time, memory-friendly for huge files |
Watch the file pointer move
with open("menu.txt") as f:
first = f.readline()
second = f.readline()
rest = f.readlines()
print(repr(first))
print(repr(second))
print(rest)
Python keeps a pointer to where it is in the file. Each read starts where the last one stopped, so readlines() only gets what is left. repr() shows the hidden \n.
Loop over the lines
with open("menu.txt") as f:
for line in f:
name, price = line.strip().split(",")
print(name.title(), "- Rs", price)
This is the pattern you will use most: one line at a time, strip() off the newline, split(",") into parts.
Every line you read keeps its \n. Print it and print adds another, so you get blank lines between rows. Compare it and "chai\n" == "chai" is False. Strip first: line.strip() (or line.rstrip("\n") to keep other spaces).
When the file is not there
try:
with open("sales.txt") as f:
print(f.read())
except FileNotFoundError:
print("No sales file yet - starting fresh")
Opening a missing file for reading raises FileNotFoundError, a runtime error you can catch like any other (Module 7).
CBSE Class 12 asks: the difference between read(), readline() and readlines() (2 marks); the advantage of with; text vs binary files; and what readline() returns at the end of the file (an empty string). Learn the return types: string, string, list.
In one line
Open files with with open(path) as f:; read() gives one string, readline() one line (with \n, "" at the end), readlines() a list; strip each line.