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:
Python Exception Handling Using try, except and finally statement
Python time Module
Partition a List in Java
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python Program to Make a Flattened List from Nested List
Python Operator Overloading
Remove All Occurrences of a Specific Value from a List
Python Set pop()
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python property()
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python Program to Convert Bytes to a String
Python Program to Display Powers of 2 Using Anonymous Function
Java – Get Random Item/Element From a List
Python id()
Python Machine Learning Eqution Reference - Sebastian Raschka
Python String capitalize()
Python String islower()
Python List Comprehension
Python Objects and Classes
Python Program to Create Pyramid Patterns
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Java Program to Implement the Program Used in grep/egrep/fgrep
Python Program to Remove Punctuations From a String
Python Program to Print Colored Text to the Terminal
Python if...else Statement
Python bin()
Remove the First Element from a List
Python strptime()
Python Program to Represent enum
Python String istitle()
How to Get Started With Python?