In this example, you will learn to read a file line by line into a list.
To understand this example, you should have the knowledge of the following Python programming topics:
1. Example 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']
readlines() returns a list of lines from the file.
- First, open the file and read the file using
readlines(). - If you want to remove the new lines (‘
\n‘), you can usestrip().
2. 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
['honda 1948\n', 'mercedes 1926\n', 'ford 1903'] ['honda 1948', 'mercedes 1926', 'ford 1903']
Another way to achieve the same thing is using a for loop. In each iteration, you can read each line of f object and store it in content_list as shown in the example above.
Related posts:
Deep Learning with Python - Francois Chollet
Python Program to Get the Full Path of the Current Working Directory
Removing all Nulls from a List in Java
Python Program to Print Output Without a Newline
Python Program to Differentiate Between type() and isinstance()
Python String splitlines()
Python abs()
Python Program to Randomly Select an Element From the List
Python Program to Display Fibonacci Sequence Using Recursion
Python Program to Generate a Random Number
Python dict()
Python Set issuperset()
Python Dictionary get()
Python bool()
Python Program to Count the Occurrence of an Item in a List
How to Find an Element in a List with Java
Python Program to Convert Two Lists Into a Dictionary
Python Machine Learning Cookbook - Practical solutions from preprocessing to Deep Learning - Chris A...
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python Program to Count the Number of Digits Present In a Number
Python String find()
Python Operator Overloading
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Python String endswith()
Python Program to Catch Multiple Exceptions in One Line
Python Program to Compute all the Permutation of the String
Python Dictionary values()
Python Program to Find Factorial of Number Using Recursion
Python Program to Check Armstrong Number
Python Program to Reverse a Number
Python List append()
Python Program to Display Calendar