Question

I am having a txt file and I want to read its lines in python. Basically I am using the following method:

f = open(description,'r')
out = f.readlines() 

for line in out:
    line

What I want is to have access in every line of the text after the for loop. Thus, to store lines in a matrix or something list-like.

Was it helpful?

Solution

Instead of readlines you could use

lines = list(open(description, 'r'))

The opened file is an iterator, that yields lines. By calling list on it, you create a list of all of them. There's no real need to keep the open file around in a variable, doing it this way it will be closed.

But using readlines() to get a list is perfectly good as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top