I want to read an entire file into a python list any one knows how to?
6 Answers
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()
1 Comment
Artsiom Rudzenka
Actually there is no need to iterate twice here - first using readlines and second using for loop
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
Comments
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()