In this article we are going to see, How we can read a file line by line using python and create a python list with each line as a list element. There are many ways to do this task and in this article we are going to cover few of them.

Suppose you are having a text file named “Text.txt” with following content.

Line 1.
Line 2.
Line 3.
How to read a file line by line in python and create a list with each line as list element.

Solution 1: Using for loop and append method.

New_list = [] 
with open("Text.txt", "r") as file:
for line in file:
New_list.append(line)
print(New_list)

#Output:
['Line 1.\n', 'Line 2.\n', 'Line 3.']

In above solution we have used python for loop:

  • Create an empty list (New_list = []).
  • Open the text file in reading mode.
  • Use the for loop to iterate through each line in text file.
  • Append each line in empty list.

Using above method we are able to create a list with each line as a list element. However If we print this list we can see the problem that, We are getting newline “\n” character added after each list element.

To remove the newline character we can use python rstrip() method. Python rstrip() method will remove the newline (\n) character from each line before appending it to the list. So the final solution becomes;

New_list = [] 
with open("Text.txt", "r") as file:
for line in file:
New_list.append(line.rstrip())
print(New_list)

#Output:
['Line 1.', 'Line 2.', 'Line 3.']

Solution 2: Using python readlines() method.

Python readlines() method reads the complete file and returns a list with each line as a list element.

with open("Text.txt", "r") as file:
new_list = file.readlines()
print
(new_list)

#Output:
['Line 1.\n', 'Line 2.\n', 'Line 3.']

Here as well we are getting newline character getting printed and to get rid of that problem, We can use python splitlines() method to resolve the newline character issue.

with open("Text.txt", "r") as file:
new_list = file.read().splitlines()
print(new_list)

#Output:
['Line 1.\n', 'Line 2.\n', 'Line 3.']

Solution 3: Using python list comprehension method.

Solving the task using List comprehension uses quite similar logic that we have seen in solution 1 the only difference is syntax. Python list comprehension requires very less code to perform the desired task.

new_list = [line.rstrip() for line in open("Text.txt", "r")]
print(new_list)

#Output:
['Line 1.', 'Line 2.', 'Line 3.']

If you want to get more information about list comprehension please go through the article. Python list comprehension along with examples.

So these were the few ways of python reading a file line by line and creating a list with each line as list element.

If you find few more ways of doing this task then please feel free to comment below.

Continue Reading:

Share this Post

Leave a Comment

Your email address will not be published.