How to read a file line-by-line into a list?
How to read a file line-by-line into a list?
Question
How do I read every line of a file in Python and store each line as an element in a list?
I want to read the file line by line and append each line to the end of the list.
Popular Answer
with open(filename) as f:
content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content]
Read more… Read less…
See Input and Ouput:
with open('filename') as f:
lines = f.readlines()
or with stripping the newline character:
with open('filename') as f:
lines = [line.rstrip() for line in f]
This is more explicit than necessary, but does what you want.
with open("file.txt") as file_in:
lines = []
for line in file_in:
lines.append(line)
This will yield an "array" of lines from the file.
lines = tuple(open(filename, 'r'))
open
returns a file which can be iterated over. When you iterate over a file, you get the lines from that file. tuple
can take an iterator and instantiate a tuple instance for you from the iterator that you give it. lines
is a tuple created from the lines of the file.
If you want the \n
included:
with open(fname) as f:
content = f.readlines()
If you do not want \n
included:
with open(fname) as f:
content = f.read().splitlines()
According to Python's Methods of File Objects, the simplest way to convert a text file into a list
is:
with open('file.txt') as f:
my_list = list(f)
If you just need to iterate over the text file lines, you can use:
with open('file.txt') as f:
for line in f:
...
Old answer:
Using with
and readlines()
:
with open('file.txt') as f:
lines = f.readlines()
If you don't care about closing the file, this one-liner works:
lines = open('file.txt').readlines()
The traditional way:
f = open('file.txt') # Open file on read mode
lines = f.read().split("\n") # Create a list containing all lines
f.close() # Close file