8

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

2
  • 1
    What tutorial are you using to learn Python? Commented Jul 16, 2011 at 21:43
  • 3
    Have you read any of the Python documentation? Commented Jul 16, 2011 at 21:44

6 Answers 6

9

Simpler:

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

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

Sign up to request clarification or add additional context in comments.

Comments

6
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

Actually there is no need to iterate twice here - first using readlines and second using for loop
4

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

1

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.

Comments

1

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

Comments

0

Another way, slightly different:

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.