Python编辑CSV标头

bar*_*l3y 7 python

我有一个名为temp的csv文件中的以下数据.

Item,Description,Base Price,Available
2000-000-000-300,AC - CF/M Series Green For Black Hood,299.99,3
2000-000-000-380,AC - CF/M Series Green For White Hood,299.99,3
Run Code Online (Sandbox Code Playgroud)

我需要更改标题才能阅读

Item Number,Item Description,List Price,QTY Available
Run Code Online (Sandbox Code Playgroud)

我一直在这里搜索类似的问题,并且没有我能理解的解决方案,因为我对python编程比较陌生.到目前为止,我有:

import csv
import os

inputFileName = "temp.csv"
outputFileName = os.path.splitext(inputFileName)[0] + "_modified.csv"

with open(inputFileName) as inFile, open(outputFileName, "w") as outfile:
    r = csv.reader(inFile)
    w = csv.writer(outfile)
Run Code Online (Sandbox Code Playgroud)

我知道只读取原始文件,然后写入_modified.如何选择当前标题然后更改它们以便它们写入新文件?

Mar*_*ers 15

标题只是另一行CSV数据.只需将它们作为新行写入输出,然后输入文件中的其余数据.

import csv
import os

inputFileName = "temp.csv"
outputFileName = os.path.splitext(inputFileName)[0] + "_modified.csv"

with open(inputFileName, 'rb') as inFile, open(outputFileName, 'wb') as outfile:
    r = csv.reader(inFile)
    w = csv.writer(outfile)

    next(r, None)  # skip the first row from the reader, the old header
    # write new header
    w.writerow(['Item Number', 'Item Description', 'List Price', 'QTY Available'])

    # copy the rest
    for row in r:
        w.writerow(row)
Run Code Online (Sandbox Code Playgroud)

对于Python 3,使用:

with open(inputFileName, newline='') as inFile, open(outputFileName, 'w', newline='') as outfile:
Run Code Online (Sandbox Code Playgroud)

并且您可能必须为数据指定编码.

  • 在Python 3中调用`next`的常用方法是`next(r)`(一个参数).对于那些使用Python 2的人来说,它将是`r.next()`.(我可以从OP的评论中推断出他对你的`next`调用没有问题.但是.) (3认同)
  • @JohnY:和`next()`在Python 2中也很有用.通过使用`next()`,你的代码在Python 2和3之间变得兼容.在Python 3中你也可以调用`r .__ next __()`但是使用`next()`更加pythonic. (2认同)