我有一个名为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)
并且您可能必须为数据指定编码.
| 归档时间: |
|
| 查看次数: |
16069 次 |
| 最近记录: |