【问题标题】:python read and process each line in file using while and for looppython使用while和for循环读取和处理文件中的每一行
【发布时间】: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


【解决方案1】:

主要问题是不必要的while循环。您遍历文本文件中的行,因此不需要它。

import csv
from string import split

f = open('GPS_SNR.csv', 'wb')

with open('EMNA_GPS.txt', 'r') as g:        
    for line in g: 
        tempstr = line.split(',')[7]
        GPSstr = tempstr.split('*')[0]
        GPS = float(GPSstr)
        wr = csv.writer(f, dialect = 'excel')
        wr.writerow([GPS])

【讨论】:

  • 他也不应该为每一行创建一个新的作家。该行应该在for 循环之前。
【解决方案2】:

for 循环将遍历文件中的每一行。 Python 自动检查文件结尾并为您关闭文件(使用with open 语法)。

import csv

with open('EMNA_GPS.txt', 'r') as g, open('GPS_SNR.csv', 'wb') as f: 
    wr = csv.writer(f, dialect = 'excel')
    for line in g: 
        tempstr = line.split(',')[7]
        GPSstr = tempstr.split('*')[0]
        print GPSstr
        GPS = float(GPSstr)
        print type(GPS)    
        wr.writerow([GPS])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-28
    • 1970-01-01
    • 2022-06-28
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多