1

I have a text file which contains multiple rows of lines, I want to store each line in a list. I have tried:

data = []
with open('numbers.txt') as f:
    data.append([int(x) for x in f.readline().split()])
print(data)

I know the above code stores only the 1st row, so how will I store rest of rows ?

Cedric
  • 408
  • 1
  • 4
  • 18

2 Answers2

1

You can iterate over the file handler to iterate over the lines in the file:

with open('numbers.txt') as f:
    data = [list(map(int, line.split())) for line in f]
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
0

This should work

with open('numbers.txt', 'r') as f:
     data = [[int(i)] for i in f.readlines()]

If you want to remove \n, then you can do something like:

with open('numbers.txt', 'r') as f:
     data = [[int(i.strip())] for i in f.readlines()]
Nalin Dobhal
  • 2,292
  • 2
  • 10
  • 20
  • 1
    No it shouldn't. You are trying to convert the whole line to int. Not entierly your fault as OP @code_freak4 didn't provide a [mre]. But guessing from his code, the lines probably look like `1 2 3 4`. You can't cast that to int – Tomerikoo Feb 21 '20 at 11:43
  • you are right, I just took the reference from the code OP provided. – Nalin Dobhal Feb 21 '20 at 11:45
  • @Tomerikoo now I am looking at this code and comparing it with accepted answer, I am getting why this answer is not correct. Thanks for pointing it out. – Nalin Dobhal Feb 21 '20 at 11:49
  • 1
    No problem. Again, not your fault as OP didn't provide an example input, what is wrong with his current output and what output he is expecting, so you couldn't quite test and compare your code – Tomerikoo Feb 21 '20 at 11:51