To read a file line by line into a list in Python, there are several approaches, each useful in different scenarios. Here are detailed explanations and examples of three such methods, including their outputs based on the content of data_file.txt
:
honda 1948
mercedes 1926
ford 1903
Example 1: Using readlines()
with open("data_file.txt") as f:
content_list = f.readlines()
# print the list with newline characters
print(content_list)
# remove newline characters
content_list = [x.strip() for x in content_list]
print(content_list)
-
with open("data_file.txt") as f:
: This opensdata_file.txt
for reading and assigns the file object tof
. Thewith
statement ensures the file is automatically closed after its block is executed. -
content_list = f.readlines()
: Reads all lines from the file into a list. Each list item contains a line from the file, including the newline character\n
at the end. -
print(content_list)
: Prints the list with newline characters. -
content_list = [x.strip() for x in content_list]
: Creates a new list where each string has been stripped of its trailing newline character using a list comprehension.
Output:
['honda 1948\n', 'mercedes 1926\n', 'ford 1903\n']
['honda 1948', 'mercedes 1926', 'ford 1903']
Example 2: Using a for loop and list comprehension
with open('data_file.txt') as f:
content_list = [line for line in f]
print(content_list)
# removing newline characters
with open('data_file.txt') as f:
content_list = [line.rstrip() for line in f]
print(content_list)
-
with open('data_file.txt') as f:
: Opensdata_file.txt
for reading. -
content_list = [line for line in f]
: A list comprehension that iterates through each line in the file, adding them to the listcontent_list
. The newline characters are included. -
print(content_list)
: Outputs the list with newline characters. - In the second
with
block,content_list = [line.rstrip() for line in f]
creates a new list, this time usingrstrip()
on each line to remove any trailing whitespace, including newline characters.
Output:
['honda 1948\n', 'mercedes 1926\n', 'ford 1903\n']
['honda 1948', 'mercedes 1926', 'ford 1903']
Example 3: Manual Line Processing
content_list = []
with open('data_file.txt', 'r') as file:
for line in file:
content_list.append(line.strip())
print(content_list)
-
content_list = []
: Initializes an empty list. -
with open('data_file.txt', 'r') as file:
: Opens the file in read mode. -
for line in file:
: Iterates over each line in the file. -
content_list.append(line.strip())
: Strips the newline character from the line and appends it tocontent_list
. -
print(content_list)
: Prints the final list without newline characters.
Output:
['honda 1948', 'mercedes 1926', 'ford 1903']
Each example demonstrates a different way of reading a file into a list in Python, with varying approaches to handling newline characters and iterating through the file's lines.
Top comments (0)