2014-10-30 75 views
-2

我有一个文本文件(coordinates.txt):阅读从文本文件坐标蟒蛇

30.154852145,-85.264584254 
15.2685169645,58.59854265854 
... 

我有一个Python脚本,里面有它while循环:

每次运行上面的循环中,我需要读取每行(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 
+2

这是_cactly_'csv'模块的用途。 – 2014-10-30 21:33:39

+0

我真的是新来的这..任何帮助将不胜感激 – user2457324 2014-10-30 21:37:20

回答

0
f=open('coordinates.txt','r') 
count =0 
for x in f: 
    x=x.strip() 
    c1,c2 = x.split(',') 
    count +=1 
+0

这留在新行,OP不会想要的。此外,它基本上只是重新创建'csv'。 – 2014-10-30 21:43:38

+0

'x = x.strip()'解决了这个问题。感谢您指出 – Hackaholic 2014-10-30 21:48:04

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. 

我也包括一种更好的方式使用利用enumeratecount变量,如通过@abarnert指出。

+1

+1。如果你需要'count',你可以使用'enumerate(reader)',而不是手动维护它。 – abarnert 2014-10-30 21:49:20

+0

@abarnert感谢提醒我,我不认为包括这一点。更新。 – 2014-10-30 21:55:19