【问题标题】:In python control the string format when writing to file in an iterator在 python 中,在迭代器中写入文件时控制字符串格式
【发布时间】:2017-08-28 14:32:21
【问题描述】:

我有一些经常以多行格式出现的数据,例如每条记录 3 行,如 r_in

name1
34
981
name2
12
321
name3
331
1299
...

我想使用 python 与数据混合,并使用 TAB 分隔值写入一个新的输出文件r_out,这里只有两列(名称和两个变量之间的比率)。

我制作了一个原始框架解析器来处理输入文件并使用 str.format() 为我提供输出。但我可能不完全理解这个函数,因为输出有些交错。或者是我使用迭代器next()的方式吗?

def parser(r_in, r_out):
   with open(r_in, "r") as r_in, open(r_out, "w") as r_out:    
     try:     
       while True:      
         #Grab the three lines with next()
         name, dat1, dat2 = next(r_in), next(r_in), next(r_in)

         #Mingle around with data, say the ratio between dat1 and dat2         
         res = round(int(dat1)/int(dat2), 2)

         #Write to r_out
         r_out.write("{}\t{}".format(name, res))

     except:
       pass

输出如下:

name1
  0.03name2
  0.04name3
  0.25me@chrx:~/projects/test$

(是的,我对 Python 比较陌生)

【问题讨论】:

    标签: python-3.x io iterator string-formatting


    【解决方案1】:

    当您在文件迭代器上调用 next 时,您会得到带有终止字符的行。

    虽然int 将其剥离,但(幸运的是)不是字符串的情况。

    所以你可以通过以下方式修复它:

    name, dat1, dat2 = next(r_in).rstrip(), next(r_in), next(r_in)
    

    您也忘记了行尾的终止。所以多合一修复:

    r_out.write("{}\t{}\n".format(name.rstrip(), res))
    

    (如果在阅读name时已经完成,则无需再次rstrip,如果在其他地方使用name更合乎逻辑,首先不需要name中的换行)

    【讨论】:

      猜你喜欢
      • 2020-07-26
      • 2011-01-30
      • 1970-01-01
      • 2019-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-12
      • 1970-01-01
      相关资源
      最近更新 更多