A file object is iterable: a for loop over it gives you one line at a time. Python does not load the whole file into memory, so this works for files of any size.
The program
python
with open("tasks.txt", "w", encoding="utf-8") as f: f.write("Buy milk\nCall Grace\n\nFinish report\n") with open("tasks.txt", encoding="utf-8") as f: for number, line in enumerate(f, start=1): line = line.strip() if not line: continue # skip empty lines print(f"{number}. {line}")
output
1. Buy milk 2. Call Grace 4. Finish report
How it works
- Each
linestill ends with\n. Without.strip(),print()would add its own new line as well, and you would see an empty line after every task. .strip()also removes spaces at the start and end. Use.rstrip("\n")if you need to keep the spaces.- An empty line in the file becomes
""after.strip(), and an empty string is false, soif not line: continueskips it. enumerate(f, start=1)counts the lines from 1. Line 3 is the empty one, so the numbers jump from 2 to 4. They match the real line numbers in the file, which helps when you report an error in a file.
All lines as a list
If the file is small and you want a list of lines, .read().splitlines() gives you the lines without the \n characters:
python
with open("tasks.txt", "w", encoding="utf-8") as f: f.write("Buy milk\nCall Grace\nFinish report\n") with open("tasks.txt", encoding="utf-8") as f: lines = f.read().splitlines() print(lines)
output
['Buy milk', 'Call Grace', 'Finish report']
Related programs: Read a file.