How to read the entire file into a list in python?
I want to read an entire file into a python list any one knows ho开发者_Go百科w to?
Simpler:
with open(path) as f:
myList = list(f)
If you don't want linebreaks, you can do list(f.read().splitlines())
print "\nReading the entire file into a list."
text_file = open("read_it.txt", "r")
lines = text_file.readlines()
print lines
print len(lines)
for line in lines:
print line
text_file.close()
Max's answer will work, but you'll be left with the endline
character (\n
) at the end of each line.
Unless that's desirable behavior, use the following paradigm:
with open(filepath) as f:
lines = f.read().splitlines()
for line in lines:
print line # Won't have '\n' at the end
Or:
allRows = [] # in case you need to store it
with open(filename, 'r') as f:
for row in f:
# do something with row
# And / Or
allRows.append(row)
Note that you don't need to care here about closing file, and also there is no need to use readlines here.
Note that Python3's pathlib
allows you to safely read the entire file in one line without writing the with open(...)
statement, using the read_text method - it will open the file, read the contents and close the file for you:
lines = Path(path_to_file).read_text().splitlines()
Another way, slightly different:
with open(filename) as f:
lines = f.readlines()
for line in lines:
print(line.rstrip())
精彩评论