Read lines into a list

EasyFile Handling Programs · 8 of 38

Write a Python program to read a file line by line into a list.

Advertisement
Output
['pen\n', 'book\n', 'bag\n']
['pen', 'book', 'bag']

Approach

  1. readlines() keeps “\n”; read().splitlines() removes it.

Solution

Python
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.

More file handling programs

← All 38 File Handling Programs

Leave a Comment