Bacco's answer explains well what the problem was, but I would like to add some comments.
The readlines
function will read the entire contents of the file at once, placing each line of the file in an item in a list. For small files - and for memory-wasting applications - this will not be a problem, but if you need to process very large files, it will be a problem. One way around this is by using generators. It is possible to work with each line of the file separately, reading one by one and doing the necessary processing. To define a generator, simply use yield
:
def list_of_integers(filename):
with open(filename) as stream:
for line in stream:
line = line.strip()
if line:
yield [int(number) for number in line.split()]
So you can scroll through all the lines as follows:
for numbers in list_of_integers('C:/Anaconda/loto.txt'):
print(numbers)
The result would be:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7, 6, 8, 9]
[3, 4, 5, 6, 7, 7, 8, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[4, 5, 6, 7, 8, 9, 10, 11]
[5, 6, 7, 6, 7, 8, 8, 9, 15]
See working at Repl.it
Other comments:
- When opening the read-only file, you can omit the mode argument,
'r'
;
- Avoid variables named
f
because they will not be readable during the code;
- If the rows in the file are too large, you may want to return a generator generator by replacing the brackets in
yield
with parentheses. In this way, the line will stay in memory only once and not twice - even if for a short time;
- The
strip
function is required because, in this case, the \n
character is held in line
;