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

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

Table of Contents

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

Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 520

Subscribe to our Newsletter

Subscribe to our newsletter and receive all latest projects...

Leave a Reply

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