Bacco’s answer explains well what the problem was, but I would like to add some comments.
The function readlines
will read the entire contents of the file at once, placing each line of the file in a list item. For small files - and for applications that waste memory - 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 set a generator, just use the 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 go 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 on Repl.it
Other comments:
- When opening the read-only file, you can omit the mode argument,
'r'
;
- Avoid variables with name
f
, because they will not be readable in the course of the code;
- If the file lines are too large too, it is convenient to return a generator generators replacing the brackets in
yield
by parentheses. This way, the line will remain in memory only once and not twice - even if for a short period of time;
- The function
strip
is therefore necessary, in that case, the character \n
is maintained in line
;
Thank you very much for the answer and the tips.
– Eduardo Marques