Python Program to Read a File Line by Line
Beginner · File handling
Reading a file line by line means handling one line at a time instead of loading the whole file at once, so even a very large file can be processed. This program writes a small text file, then reads it back one line at a time and prints each line with its number.
Program
Line 1: Python is easy to read Line 2: Files keep data after the program ends Line 3: Practice a little every day
How it works
- The program first writes three lines to
notes.txt, each ending in\n, so it has a file to read. with open("notes.txt", "r") as fopens the file for reading and closes it automatically when the block ends.for line in fgives one line of the file on each pass, without loading the whole file into memory.- Every line read from a file still ends with its newline, so
line.rstrip()removes it; otherwiseprint()would leave a blank line after each one. line_numberstarts at 1 and goes up by one each time, so every line is printed with its number.
Other ways to write it
Using readline() in a while loop
Python is easy to read Files keep data after the program ends Practice a little every day
readline() reads one more line each time it is called and returns an empty string at the end of the file. A blank line inside the file comes back as "\n", not "", so it does not end the loop early.
Using readlines() and enumerate()
The file has 3 lines 1 Python is easy to read 2 Files keep data after the program ends 3 Practice a little every day
readlines() loads every line into a list at once, which is handy when you need the count or want to go back to a line, but for line in f uses less memory on big files.
Try it yourself
Add a blank line to the sample file and change the loop so it skips empty lines instead of printing them.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Count the Lines in a File
- Write to a File
- Read a Text File and Separate Words with #
- Find the Longest Line in a File
- Count Vowels, Consonants, Uppercase and Lowercase Characters in a Text File
- Copy Lines Without the Letter 'a' to Another File
- Search a Roll Number in a Binary File
- Update Marks in a Binary File
- Store and Search User IDs and Passwords in a CSV File
- Count the Words "Me" and "My" in a Text File
All Python programs · CBSE class 12 practical file · Python exercises