【问题标题】:Python: Writing certain columns specified by user to new filePython:将用户指定的某些列写入新文件
【发布时间】:2018-12-06 13:20:36
【问题描述】:

如果我有一个包含多列的文件,例如

0, 1, 2, 3, 4, 5, 6
a, b, c, d, e, f, g

我想将某些列写入一个新文件,其中列号存储在列表col=[] 中。如何使用存储在列表中的列号的迭代来复制结果,例如:

new_file.write(line[0]+','+line[5]+','+line[6]+'\n')

我试过了:

col = [0,5,6]
for line in file:
   new_file.write(line[i] for i in col)

但是这不起作用,我在最后一行出现类型错误。最后,我希望用户输入列表,以便输出文件仅包含用“”分隔的指定列,就像上面的 exaple 文件一样。

【问题讨论】:

  • 首先使用csv 模块,因为for line in file 会产生完整的行,而不是像 csv 这样的字段

标签: python python-2.7 file-writing


【解决方案1】:

for line in file: 迭代每一行的每个字符,而不是你想要的。

与逗号分隔的文件一样,您应该使用csv 模块正确读取字段,并使用相同的csv 模块将它们写回:

import csv

col = [0,5,6]

with open("input.csv") as fr, open("output.csv","w",newline="") as fw:
    cr = csv.reader(fr)
    cw = csv.writer(fw)
    cw.writerows([row[i] for i in col] for row in cr)

创建:

0, 5, 6
a, f, g

Python 2.7 需要将 open("output.csv","w",newline="") 更改为 open("output.csv","wb")

【讨论】:

    【解决方案2】:

    您必须先拆分列,因为它们以单个字符串的形式出现,最好使用str.join 将它们粘在一起:

    col = [0,5,6]
    for line in file:
       line = line.split()
       new_file.write(", ".join(line[i] for i in col))
    

    【讨论】:

      猜你喜欢
      • 2016-02-22
      • 1970-01-01
      • 1970-01-01
      • 2021-05-02
      • 2018-02-09
      • 1970-01-01
      • 2012-02-24
      • 2021-05-14
      • 1970-01-01
      相关资源
      最近更新 更多