我有一个文本文件:
30.154852145,-85.264584254
15.2685169645,58.59854265854
...
我有以下python脚本:
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
我想要c1 = 15.2685169645
val: 2
。有人可以告诉我我搞砸了什么吗?
答案 0 :(得分:3)
每次重新打开文件,都会重新开始阅读。
只需打开一次文件:
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
这也将文件对象用作a context manager,因此with
语句会在您完成后关闭它,并使用enumerate()
进行计数。
答案 1 :(得分:1)
使用你自己的循环:
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