Welcome to the World of Online Learning:
Hello Friends “This blog helps you to learn Python programming concepts. You can learn Python language at your own speed and time. One can learn concepts of Python language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”
Write a Python Program Read a File Line by Line Into a List
PROGRAM: Python Program Read a File Line by Line Into a List
/* Python Program Read a File Line by Line Into a List */
1: Using readlines()
Let the content of the file data_file.txt be
honda 1948
mercedes 1926
ford 1903
Source code
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:-
['honda 1948\n', 'mercedes 1926\n', 'ford 1903'] ['honda 1948', 'mercedes 1926', 'ford 1903']
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:-
['honda 1948\n', 'mercedes 1926\n', 'ford 1903'] ['honda 1948', 'mercedes 1926', 'ford 1903']