Python Practice › File Handling Programs › Program 8
Read lines into a list
Write a Python program to read a file line by line into a list.
Output
['pen\n', 'book\n', 'bag\n'] ['pen', 'book', 'bag']
Approach
readlines()keeps “\n”;read().splitlines()removes it.
Solution
with open("items.txt", "w") as f: f.write("pen\nbook\nbag\n") with open("items.txt") as f: print(f.readlines())with open("items.txt") as f: print([line.rstrip("\n") for line in f])Output
['pen\n', 'book\n', 'bag\n'] ['pen', 'book', 'bag']
Learn the concept
New to this topic? Read the lesson, then come back.