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
Shailendra Bramhvanshi, Founder at Techaroha Solutions Private Limited and CEO at Newtum Solutions Private Limited. BlockChain Experts with 12 years of IT Experience in of all aspects of running Organization and Project Management. I have created different coins to help the business to bring more trust. Recently deployed a stable coin in India TrueINR and working on few cryptocurrency exchanges. My Team is being rated as a top 10 blockchain service provider in India by Silicon India