Reading a file line by line is a common task in programming, especially when working with large files that cannot be read in memory at once. Python provides a simple and efficient way of reading files line by line using built-in functions.
Steps to Read Line By Line in Python:
Let’s create a file named “sample.txt” with the following content:
This is the first line. This is the second line. And this is the third line.
Now, let’s use Python to read this file line by line and print each line.
1 2 3 4 5 6 |
file = open('sample.txt', 'r') for line in file: print(line) file.close() |
This will output:
Output:
This is the first line. This is the second line. And this is the third line.
Conclusion:
In this tutorial, we learned how to read a file line by line in Python using a simple for
loop. This technique is useful when working with large files that cannot be loaded into memory at once. Remember to always close the file using the close()
function after reading it.