How to read a file line by line in Python

by Alex
How to read a file line by line in Python

There are many ways to read from a file line by line in Python. You can read lines into a list or access each line in a loop using an iterator or function call to the file object. In this tutorial, we will learn how to read a file line by line using readline(), readlines(), and a file object using examples of various programs.

Example 1: Read a file line by line with readline()

In this example, we will use readline() for a file object, retrieving each line in a loop.

How to use file.readline()

Follow the steps below to read a file line by line using readline().

  1. Open the file in read mode. This will return the file descriptor.
  2. Create an infinite while loop.
    1. In each iteration we read the file line with readline().
    2. If the line is not empty, we output it and move on to the next line. You can check this by using the if not construction. Otherwise the file has no more lines and we stop the loop with break.
  3. By the time we exit the loop, we count all the lines of the file in iterations one by one.
  4. After that we close the file using the close function.

# get the file object
file1 = open("sample.txt", "r")
while True:
# we read the line
line = file1.readline()
# interrupt the loop if the line is empty
if not line:
break
# print the line
print(line.strip())
# close the file
file1.close

Output:

Hi!
Welcome to PythonRu.
Good luck learning!

Example 2: Reading strings as a list with readlines()

The readlines() function returns all the lines in a file as a list. We can go through the list and access each line. In the following program, we have to open a text file and get a list of all its lines using the readlines() function. After that, we use the for loop to bypass this list.

# get the file object
file1 = open("sample.txt", "r")
# read all lines
lines = file1.readlines()
# iterate through the lines
for lines in lines:
print(line.strip())
# close the file
file1.close
Hi!
Welcome to PythonRu.
Good luck with your learning!

Example 3: Read the file line by line from the File object

In our first example, we read each line of the file using the infinite while loop and readline() function. But you can use the for loop for the file object to get a line in each iteration of the loop until the end of the file is reached. Below is a program that demonstrates the use of the for-in statement to go through the lines of a file. For this demonstration, we open the file with open. This also applies to the previous two examples.


# get the file object
with open("sample.txt", "r") as file1:
# iterate over lines
for line in file1:
print(line.strip())
Hi!
Welcome to PythonRu.
Good luck in learning!

Conclusions

In this tutorial we learned how to read a text file line by line using example Python programs.

Related Posts

LEAVE A COMMENT