Algorithm


  1. User Input:

    • Get the file path or name from the user.
  2. Open File:

    • Use the open function to open the file in read mode.
  3. Read Lines Into List:

    • Use a loop to iterate over the file object, reading each line and appending it to a list.
  4. Close File:

    • Close the file using the close method.

 

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

x
+
cmd
['honda 1948\n', 'mercedes 1926\n', '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

x
+
cmd
['honda 1948\n', 'mercedes 1926\n', 'ford 1903']
['honda 1948', 'mercedes 1926', 'ford 1903']
Advertisements

Demonstration


Python Programing Example Read a File Line by Line Into a List-DevsEnv