Reputation: 141
I have a text file:
30.154852145,-85.264584254
15.2685169645,58.59854265854
...
I have the following python script:
count = 0
while True:
count += 1
print 'val:',count
for line in open('coords.txt'):
c1, c2 = map(float, line.split(','))
break
print 'c1:',c1
if count == 2: break
I want c1 = 15.2685169645
for val: 2
. Can someone please tell me what I am messing up on?
Upvotes: 1
Views: 68
Reputation: 180391
Using your own loop:
with open('coords.txt') as f:
count = 1
while True:
for line in f:
print 'val: {}'.format(count)
c1, c2 = map(float, line.split(','))
print("c1 = {!r}".format(c1))
if count == 2:
break
count += 1
break
Upvotes: 1
Reputation: 1121236
By reopening the file each time, you start reading from the start again.
Just open the file once:
with open('coords.txt') as inputfile:
for count, line in enumerate(inputfile, 1):
c1, c2 = map(float, line.split(','))
print 'c1:',c1
if count == 2: break
This also uses the file object as a context manager so the with
statement will close it for you once done, and uses enumerate()
to do the counting.
Upvotes: 3