Algorithm
-
User Input:
- Get the file path or name from the user.
-
Open File:
- Use the
open
function to open the file in read mode.
- Use the
-
Read Lines Into List:
- Use a loop to iterate over the file object, reading each line and appending it to a list.
-
Close File:
- Close the file using the
close
method.
- Close the file using the
Code Examples
#1 Code Example- Python Programing Using readlines()
Code -
Python Programming
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)
Copy The Code &
Try With Live Editor
Output
['honda 1948\n', 'mercedes 1926\n', 'ford 1903']
['honda 1948', 'mercedes 1926', 'ford 1903']
['honda 1948', 'mercedes 1926', 'ford 1903']
#2 Code Example- Python Programing Using for loop and list comprehension
Code -
Python Programming
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)
Copy The Code &
Try With Live Editor
Output
['honda 1948\n', 'mercedes 1926\n', 'ford 1903']
['honda 1948', 'mercedes 1926', 'ford 1903']
['honda 1948', 'mercedes 1926', 'ford 1903']
Demonstration
Python Programing Example Read a File Line by Line Into a List-DevsEnv