Mir Khashkhash
Mir Khashkhash

Reputation: 399

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 how to?

Upvotes: 8

Views: 13726

Answers (6)

misterrodger
misterrodger

Reputation: 225

Another way, slightly different:

with open(filename) as f:
    lines = f.readlines()

for line in lines:
    print(line.rstrip())

Upvotes: 0

Aleph Aleph
Aleph Aleph

Reputation: 5395

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()

Upvotes: 1

Srini
Srini

Reputation: 1646

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

Upvotes: 4

ninjagecko
ninjagecko

Reputation: 91139

Simpler:

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

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

Upvotes: 9

Max
Max

Reputation: 4408

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()

Upvotes: 6

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29121

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.

Upvotes: 1

Related Questions