Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read the entire file into a list in python?

Tags:

python

I want to read an entire file into a python list any one knows how to?

like image 519
Mir Khashkhash Avatar asked Jul 16 '11 21:07

Mir Khashkhash


2 Answers

Simpler:

with open(path) as f:
    myList = list(f)

If you don't want linebreaks, you can do list(f.read().splitlines())

like image 107
ninjagecko Avatar answered Oct 02 '22 19:10

ninjagecko


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()
like image 32
Max Avatar answered Oct 02 '22 19:10

Max