Python编辑CSV头

2024-05-15 17:52:34 发布

您现在位置: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

我需要把标题改成

Item Number,Item Description,List Price,QTY Available

我一直在这里搜索类似的问题,由于我对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)

我知道它只读取原始文件,然后将修改后的文件写入。如何选择当前标题,然后对其进行更改,使其写入新文件?


Tags: 文件csv标题forgreendescriptionitemprice
3条回答

您可以使用fileinput来执行以下操作:

import fileinput
import sys
import os

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

with open(outputFileName, "w") as outfile:
    for line in fileinput.input(
        [inputFileName],
        inplace=False):
        if fileinput.isfirstline():
            outfile.write('Item Number,Item Description,List Price,QTY Available\n')
        else:
            outfile.write(line)

标题只是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)

对于Python3,使用:

with open(inputFileName, newline='') as inFile, open(outputFileName, 'w', newline='') as outfile:

您可能需要为数据指定编码。

另一种解决方案是使用fileinput模块就地更新文件:

import fileinput
for line in fileinput.input('temp', inplace=True):
    if fileinput.isfirstline():
        print 'Item Number,Item Description,List Price,QTY Available'
    else:
        print line,

相关问题 更多 >