Help us understand the problem. What is going on with this article?

Python - Most elegant way to read lines of file into list

More than 5 years have passed since last update.

Ref:
[1] - Python: read file line by line into array

For most cases, to read lines of file to a list, we just use

with open(fileName) as f:
  lineList = f.readlines()

In this case, every element in the list contain a \n in the end the string, which would be extremely annoying in some cases.

And there will be same problem if you use:

lineList = list()
with open(fileName) as f:
  for line in f:
    lineList.append(line)

To overcome this, you could use:

lineList = [line.rstrip('\n') for line in open(fileName)]
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away