我希望在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])
答案 0 :(得分:3)
我认为你可以做到:
import csv
SDict = {'T1': 'A', 'T2': 'B', 'T4': 'D'}
with open('file.csv', 'r+b') as f:
header = next(csv.reader(f))
dict_writer = csv.DictWriter(f, header, -999)
dict_writer.writerow(SDict)
这假设您使用的是Python 2.X.另外,要警惕不以换行符结尾的文件,否则最终会出现7,8,9,10,11A,B,-999,D,-999
之类的行。