我正在寻找将我必须的字典附加到 CSV 文件中,如果我已经有一个标题行并且如果一个值不存在我想写'-999'
:
SDict ={T1:'A',T2:'B',T4:'D')
其中 CSV 文件的标题为
T1,T2,T3,T4,T5
7,8,9,10,11
和预期的结果是
T1,T2,T3,T4,T5
7,8,9,10,11
A,B,-999,D,-999
我正在尝试使用代码这样做:
import sys
import os
import csv
def GetFileHeader(Fpath):
i=10
ResFile=open (Fpath, 'r+')
HeaderDict={}
r=csv.reader(ResFile)
HeaderList = r.next()
for Header in HeaderList:
HeaderDict[Header]=i+1
print HeaderDict
ResFile.close()
return HeaderDict
Fpath= r'Z:\temp\assaf\S2TTP\S2T_TP\modules\results\Y124\res.csv'
Header= GetFileHeader(Fpath)
with open(Fpath,'rb') as fin:
dr = csv.DictReader(fin, dialect='excel')
print dr
print dr.fieldnames
# dr.fieldnames contains values from first row of `f`.
with open(Fpath,'ab+') as fou:
dw = csv.DictWriter(fou, dialect='excel', fieldnames=dr.fieldnames)
fieldnames=dr.fieldnames
for K in fieldnames:
dw.writerow(Header[k])