Read a File Line by Line Into a List in Python

Python Program to Read a File Line by Line Into a List using readlines()

# Python Program to Read a File Line by Line Into a List using readlines() 

# Open the file in read mode
with open('test.txt', 'r') as file:
    # Read all the lines of the file into a list
    lines = file.readlines()

# Print the list of lines
print(lines)

Output:

['line1\n' , 'line2\n' , 'line3']
['line1' , 'line2' , 'line3']

Python Program to Read a File Line by Line Into a List using loop and list comprehension

# Python Program to Read a File Line by Line Into a List using loop and  list comprehension

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

print(content_list)

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

print(content_list)

Output:

['line1\n' , 'line2\n' , 'line3']
['line1' , 'line2' , 'line3']

About The Author

Leave a Reply