second In Python, how do I read a file line-by-line into a list?
python3 read file line by line (24)
The simplest way to do it
A simple way is to:
- Read the whole file as a string
- Split the string line by line
In one line, that would give:
lines = open('C:/path/file.txt').read().splitlines()
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.
See Input and Ouput:
with open('filename') as f: lines = f.readlines()
or with stripping the newline character:
lines = [line.rstrip('\n') for line in open('filename')]
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
Here's one more option by using list comprehensions on files;
lines = [line.rstrip() for line in open('file.txt')]
This should be more efficient way as the most of the work is done inside the Python interpreter.
f = open("your_file.txt",'r') out = f.readlines() # will append in the list out
Now variable out is a list (array) of what you want. You could either do:
for line in out: print line
for line in f: print line
you'll get the same results.
I'd do it like this.
lines =  with open("myfile.txt") as f: for line in f: lines.append(line)
This should encapsulate the open command.
array =  with open("file.txt", "r") as f: for line in f: array.append(line)
To my knowledge Python doesn't have a native array data structure. But it does support the list data structure which is much simpler to use than an array.
array =  #declaring a list with name '**array**' with open(PATH,'r') as reader : for line in reader : array.append(line)
This is more explicit than necessary, but does what you want.
with open("file.txt", "r") as ins: array =  for line in ins: array.append(line)
If you'd like to read a file from the command line or from stdin, you can also use the
# reader.py import fileinput content =  for line in fileinput.input(): content.append(line.strip()) fileinput.close()
Pass files to it like so:
$ python reader.py textfile.txt
Read more here: http://docs.python.org/2/library/fileinput.html
I like to use the following. Reading the lines immediately.
contents =  for line in open(filepath, 'r').readlines(): contents.append(line.strip())
Or using list comprehension:
contents = [line.strip() for line in open(filepath, 'r').readlines()]
You could also use the loadtxt command in NumPy. This checks for fewer conditions than genfromtxt, so it may be faster.
import numpy data = numpy.loadtxt(filename, delimiter="\n")
import pandas as pd data = pd.read_csv(filename) # You can also add parameters such as header, sep, etc. array = data.values
data is a dataframe type, and uses values to get ndarray. You can also get a list by using
If you don't care about closing the file, this one-liner works:
lines = open('file.txt').read().split("\n")
The traditional way:
fp = open('file.txt') # Open file on read mode lines = fp.read().split("\n") # Create a list containing all lines fp.close() # Close file
with open('file.txt') as fp: lines = fp.read().split("\n")
Another option is
numpy.genfromtxt, for example:
import numpy as np data = np.genfromtxt("yourfile.dat",delimiter="\n")
This will make
data a NumPy array with as many rows as are in your file.
To read a file into a list you need to do three things:
- Open the file
- Read the file
- Store the contents as list
Fortunately Python makes it very easy to do these things so the shortest way to read a file into a list is:
lst = list(open(filename))
However I'll add some more explanation.
Opening the file
I assume that you want to open a specific file and you don't deal directly with a file-handle (or a file-like-handle). The most commonly used function to open a file in Python is
open, it takes one mandatory argument and two optional ones in Python 2.7:
- Buffering (I'll ignore this argument in this answer)
The filename should be a string that represents the path to the file. For example:
open('afile') # opens the file named afile in the current working directory open('adir/afile') # relative path (relative to the current working directory) open('C:/users/aname/afile') # absolute path (windows) open('/usr/local/afile') # absolute path (linux)
Note that the file extension needs to be specified. This is especially important for Windows users because file extensions like
.doc, etc. are hidden by default when viewed in the explorer.
The second argument is the
r by default which means "read-only". That's exactly what you need in your case.
But in case you actually want to create a file and/or write to a file you'll need a different argument here. There is an excellent answer if you want an overview.
For reading a file you can omit the
mode or pass it in explicitly:
open(filename) open(filename, 'r')
Both will open the file in read-only mode. In case you want to read in a binary file on Windows you need to use the mode
On other platforms the
'b' (binary mode) is simply ignored.
Now that I've shown how to
open the file, let's talk about the fact that you always need to
close it again. Otherwise it will keep an open file-handle to the file until the process exits (or Python garbages the file-handle).
While you could use:
f = open(filename) # ... do stuff with f f.close()
That will fail to close the file when something between
close throws an exception. You could avoid that by using a
f = open(filename) # nothing in between! try: # do stuff with f finally: f.close()
However Python provides context managers that have a prettier syntax (but for
open it's almost identical to the
with open(filename) as f: # do stuff with f # The file is always closed after the with-scope ends.
The last approach is the recommended approach to open a file in Python!
Reading the file
Okay, you've opened the file, now how to read it?
open function returns a
file object and it supports Pythons iteration protocol. Each iteration will give you a line:
with open(filename) as f: for line in f: print(line)
This will print each line of the file. Note however that each line will contain a newline character
\n at the end (you might want to check if your Python is built with universal newlines support - otherwise you could also have
\r\n on Windows or
\r on Mac as newlines). If you don't want that you can could simply remove the last character (or the last two characters on Windows):
with open(filename) as f: for line in f: print(line[:-1])
But the last line doesn't necessarily has a trailing newline, so one shouldn't use that. One could check if it ends with a trailing newline and if so remove it:
with open(filename) as f: for line in f: if line.endswith('\n'): line = line[:-1] print(line)
But you could simply remove all whitespaces (including the
\n character) from the end of the string, this will also remove all other trailing whitespaces so you have to be careful if these are important:
with open(filename) as f: for line in f: print(f.rstrip())
However if the lines end with
\r\n (Windows "newlines") that
.rstrip() will also take care of the
Store the contents as list
Now that you know how to open the file and read it, it's time to store the contents in a list. The simplest option would be to use the
with open(filename) as f: lst = list(f)
In case you want to strip the trailing newlines you could use a list comprehension instead:
with open(filename) as f: lst = [line.rstrip() for line in f]
Or even simpler: The
.readlines() method of the
file object by default returns a
list of the lines:
with open(filename) as f: lst = f.readlines()
This will also include the trailing newline characters, if you don't want them I would recommend the
[line.rstrip() for line in f] approach because it avoids keeping two lists containing all the lines in memory.
There's an additional option to get the desired output, however it's rather "suboptimal":
read the complete file in a string and then split on newlines:
with open(filename) as f: lst = f.read().split('\n')
with open(filename) as f: lst = f.read().splitlines()
These take care of the trailing newlines automatically because the
split character isn't included. However they are not ideal because you keep the file as string and as a list of lines in memory!
with open(...) as fwhen opening files because you don't need to take care of closing the file yourself and it closes the file even if some exception happens.
fileobjects support the iteration protocol so reading a file line-by-line is as simple as
for line in the_file_object:.
- Always browse the documentation for the available functions/classes. Most of the time there's a perfect match for the task or at least one or two good ones. The obvious choice in this case would be
readlines()but if you want to process the lines before storing them in the list I would recommend a simple list-comprehension.
You could simply do the following, as has been suggested:
with open('/your/path/file') as f: my_lines = f.readlines()
Note that this approach has 2 downsides:
1) You store all the lines in memory. In the general case, this is a very bad idea. The file could be very large, and you could run out of memory. Even if it's not large, it is simply a waste of memory.
2) This does not allow processing of each line as you read them. So if you process your lines after this, it is not efficient (requires two passes rather than one).
A better approach for the general case would be the following:
with open('/your/path/file') as f: for line in f: process(line)
Where you define your process function any way you want. For example:
def process(line): if 'save the world' in line.lower(): superman.save_the_world()
(The implementation of the
Superman class is left as an exercise for you).
This will work nicely for any file size and you go through your file in just 1 pass. This is typically how generic parsers will work.
If you want to are faced with a very large / huge file and want to read faster (imagine you are in a Topcoder/Hackerrank coding competition), you might read a considerably bigger chunk of lines into a memory buffer at one time, rather than just iterate line by line at file level.
buffersize = 2**16 with open(path) as f: while True: lines_buffer = f.readlines(buffersize) if not lines_buffer: break for line in lines_buffer: process(line)
This will yield an "array" of lines from the file.
lines = tuple(open(filename, 'r'))
Read and write text files with Python 2 and Python 3; it works with Unicode
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Define data lines = [' A first string ', 'A Unicode sample: €', 'German: äöüß'] # Write text file with open('file.txt', 'w') as fp: fp.write('\n'.join(lines)) # Read text file with open('file.txt', 'r') as fp: read_lines = fp.readlines() read_lines = [line.rstrip('\n') for line in read_lines] print(lines == read_lines)
Things to notice:
withis a so-called context manager. It makes sure that the opened file is closed again.
- All solutions here which simply make
.rstrip()will fail to reproduce the
linesas they also strip the white space.
Common file endings
More advanced file writing / reading
- CSV: Super simple format (read & write)
- JSON: Nice for writing human-readable data; VERY commonly used (read & write)
- YAML: YAML is a superset of JSON, but easier to read (read & write, comparison of JSON and YAML)
- pickle: A Python serialization format (read & write)
- MessagePack (Python package): More compact representation (read & write)
- HDF5 (Python package): Nice for matrices (read & write)
- XML: exists too *sigh* (read & write)
For your application, the following might be important:
- Support by other programming languages
- Reading / writing performance
- Compactness (file size)
See also: Comparison of data serialization formats
In case you are rather looking for a way to make configuration files, you might want to read my short article Configuration files in Python.
You can just open your file for reading using:
file1 = open("filename","r") # And for reading use lines = file1.readlines() file1.close()
lines will contain all your lines as individual elements, and you can call a specific element using
lines["linenumber-1"] as Python starts its counting from 0.
Command line version
#!/bin/python3 import os import sys abspath = os.path.abspath(__file__) dname = os.path.dirname(abspath) filename = dname + sys.argv arr = open(filename).read().split("\n") print(arr)
python3 somefile.py input_file_name.txt
Just use the splitlines() functions. Here is an example.
inp = "file.txt" data = open(inp) dat = data.read() lst = dat.splitlines() print lst # print(lst) # for python 3
In the output you will have the list of lines.
If you want the
with open(fname) as f: content = f.readlines()
If you do not want
with open(fname) as f: content = f.read().splitlines()
You can easily do it by the following piece of code:
lines = open(filePath).readlines()