Reputation: 8172
with open('index.txt','r') as f:
a = [int(x) for x in f.readline().split()]
array = []
for line in f:
array.append([int(x) for x in line.split()])
print array[0]
print array[1]
print array[2]
print array[3]
print array[4]
The input file
0
0
100
200
1
101
201
2
102
202
3
103
When I run my code
[0]
[100]
[200]
[1]
[101]
Just second 0
appears.
Upvotes: 0
Views: 1035
Reputation: 5514
The issue is this line:
a = [int(x) for x in f.readline().split()]
This is exhausting the first line of the file iterator, so when you then loop through the remaining lines, you've already consumed the first one.
To fix the issue, either remove this line of code, or if you need it, generate a list of file contents (f.readlines()
) and iterate through the list, or seek back to the file start after that line (f.seek(0)
). Note that if your file is particularly large, f.readlines()
should be avoided as this will bring the entire file into memory.
Upvotes: 5
Reputation: 404
If this file is simply a list of integers numpy might offer a much easier solution:
import numpy
array = numpy.loadtxt('index.txt', dtype=int)
Upvotes: 0