Two ways to read a file to a list in python (note that they are not either) -
- using
with - supported with python 2.5 and higher - using list concepts
1. use with
This is a pythonic way to open and read files.
#Sample 1 - elucidating each step but not memory efficient lines = [] with open("C:\name\MyDocuments\numbers") as file: for line in file: line = line.strip() #or some other preprocessing lines.append(line) #storing everything in memory! #Sample 2 - a more pythonic and idiomatic way but still not memory efficient with open("C:\name\MyDocuments\numbers") as file: lines = [line.strip() for line in file] #Sample 3 - a more pythonic way with efficient memory usage. Proper usage of with and file iterators. with open("C:\name\MyDocuments\numbers") as file: for line in file: line = line.strip() #preprocess line doSomethingWithThisLine(line) #take action on line instead of storing in a list. more memory efficient at the cost of execution speed.
.strip() used for each line of the file to remove the \n newline character that each line can have. When the with end ends, the file will be automatically closed for you. This is true even if an exception occurs in it.
2. using list comprehension
This can be considered inefficient because the file descriptor cannot be closed immediately. It can be a potential problem when it is called inside a function that opens thousands of files.
data = [line.strip() for line in open("C:/name/MyDocuments/numbers", 'r')]
Note that closing the file is implementation dependent. Usually unused variables are garbage collected by the python interpreter. In cPython (a version of the regular interpreter from python.org) this will happen immediately, since the garbage collector works by reference counting. There may be a delay in another interpreter, such as Jython or Iron Python.
Srikar Appalaraju Oct 13 2018-10-10 16:48
source share