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.
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.
I'd do it like this.
Use this:
data
is a dataframe type, and uses values to get ndarray. You can also get a list by usingarray.tolist()
.See Input and Ouput:
or with stripping the newline character:
Editor's note: This answer's original whitespace-stripping command,
line.strip()
, as implied by Janus Troelsen's comment, would remove all leading and trailing whitespace, not just the trailing\n
.This will yield an "array" of lines from the file.
Just use the splitlines() functions. Here is an example.
In the output you will have the list of lines.
If you'd like to read a file from the command line or from stdin, you can also use the
fileinput
module:Pass files to it like so:
Read more here: http://docs.python.org/2/library/fileinput.html