我有一个文本文件(coordinates.txt
):
30.154852145,-85.264584254
15.2685169645,58.59854265854
...
我有一个python脚本,里面有一个while循环:
count = 0
while True:
count += 1
c1 =
c2 =
对于上述循环的每次运行,我需要读取每一行(count)并将c1,c2
设置为每行的数字(用逗号分隔)。有人可以告诉我最简单的方法吗?
============================
import csv
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
答案 0 :(得分:3)
最好的方法是,正如我上面评论的那样:
import csv
with open('coordinates.txt') as f:
reader = csv.reader(f)
for count, (c1, c2) in enumerate(reader):
# Do what you want with the variables.
# You'll probably want to cast them to floats.
正如@abarnert所指出的那样,我还提供了一种使用count
使用enumerate
变量的更好方法。
答案 1 :(得分:0)
f=open('coordinates.txt','r')
count =0
for x in f:
x=x.strip()
c1,c2 = x.split(',')
count +=1