Python编辑CSV标题
我有一个名为temp的csv文件中的以下数据Python编辑CSV标题,python,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 Availab
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)
据我所知,它只读取原始文件,然后将写入修改后的文件。如何选择当前标题,然后将其更改为写入新文件?标题只是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)
对于Python 3,请使用:
with open(inputFileName, newline='') as inFile, open(outputFileName, 'w', newline='') as outfile:
您可能需要为数据指定编码。您可以使用以下方法:
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)
另一种解决方案是使用
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,
Python 3中调用
next
的常用方法是next(r)
(一个参数)。对于那些使用Python 2的人来说,应该是r.next()
。(不过,我可以从OP的评论中推断,他对你的下一个调用没有问题。@barkl3y:是的,首先将所有参数分组到一个列表或元组中。(只需在参数周围放一对方括号或第二组括号。)@JohnY:next()
采用默认值。如果r
为空,next(r)
抛出StopIteration
,而next(r,None)
返回默认的None
。@JohnY:andnext()
在Python 2中也很有效。通过使用next()
您的代码在Python 2和Python 3之间变得兼容。在Python3中,您也可以调用r.\uuuu next.\uuuu()
,但是使用next()
更像Python。啊,老习惯next()
是在Python2.6中引入的,我使用Python的一个平台直到最近才停留在2.3.3中。