【发布时间】:2016-07-08 17:36:34
【问题描述】:
输入:一个 .txt 文件包含很多行 '$GPGSV,1,1,01,01,,,26*7D'
输出:26
import subprocess
import csv
from string import split
f = open('GPS_SNR.csv', 'wb')
while True:
with open('EMNA_GPS.txt', 'r') as g:
for line in g:
tempstr = line.split(',')[7]
GPSstr = tempstr.split('*')[0]
print GPSstr
GPS = float(GPSstr)
print type(GPS)
wr = csv.writer(f, dialect = 'excel')
wr.writerow([GPS])
g.close()
会发生什么: 无限循环永远不会停止......可以说文件中有100行;但是,.csv 中写入了数千行而不是 100 行。
我应该使用 'if = EOF' 语句吗?
【问题讨论】:
-
那是因为你从来没有在你的
while True:循环上调用break。 -
一些注意事项:A)您使用
with语句打开g;您不需要(也不应该)明确地close它,这就是with语句为您所做的。 B) 你应该使用with语句打开f(你忽略了close;如果文件打开写不这样做更有可能导致问题)。 C) 删除from string import split;这是一个古老的 API;str上的split方法不需要特殊导入。 D) 那个文本文件看起来真的是 CSV;有什么理由不这样解析它?如果数据实际上是 CSV 数据,则文件扩展名并不重要。
标签: python if-statement for-loop while-loop