Python Program to Read a File Line by Line Into a List – 2022

Machine Learning Projects

Hey guys, in this blog we will see a Python Program to Read a File Line by Line Into a List.

Example 1: Using readlines()

Let the content of the file data_file.txt be

Machine Learning Projects
Deep Learning Projects
Flask Projects

with open("data_file.txt") as f:
    content_list = f.readlines()

# print the list
print(content_list)

# remove new line characters
content_list = [x.strip() for x in content_list]
print(content_list)

Output

['Machine Learning Projects\n', 'Deep Learning Projects\n', 'Flask Projects']
['Machine Learning Projects', 'Deep Learning Projects', 'Flask Projects']
  • readlines() returns a list of lines from the file.
  • strip() will just remove the extra ‘\n’ characters from both ends of the elements of the list.

Example 2: Using for loop and list comprehension

with open('data_file.txt') as f:
    content_list = [line for line in f]

print(content_list)

# removing the characters
with open('data_file.txt') as f:
    content_list = [line.rstrip() for line in f]

print(content_list)

Output

['Machine Learning Projects\n', 'Deep Learning Projects\n', 'Flask Projects']
['Machine Learning Projects', 'Deep Learning Projects', 'Flask Projects']

Check out our other python programming examples

Leave a Comment

Your email address will not be published. Required fields are marked *