【问题标题】:Start reading and writing on specific line on CSV with Python使用 Python 在 CSV 上的特定行上开始读写
【发布时间】:2012-07-24 02:32:19
【问题描述】:

我有一个如下所示的 CSV 文件:

COL_A,COL_B
12345,A=1$B=2$C=3$

如何读取该文件并将其写回一个新文件,但只是第二行(行)? 我希望输出文件包含:

12345,A=1$B=2$C=3$

谢谢!

【问题讨论】:

  • COL_B 和 12345 之间有逗号吗?

标签: python csv


【解决方案1】:

以下内容读取您的 csv,提取第二行,然后将第二行写入另一个文件。

with open('file.csv') as file:
    second_line = list(file)[1]

with open('out.csv', mode = 'w') as file:
    file.write(second_line)

【讨论】:

    【解决方案2】:
    outfile = open(outfilename,"w")
    with open(filename) as f:
        for line in f:
           print >> outfile , line.split()[-1]
    outfile.close()
    

    只要这些行看起来像您在 OP 中发布的行

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 2019-05-12
      • 2015-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多