我非常接近完成,但无法解决这个问题。我正在写信给 csv,我的代码一直给我这个输出。
dict,a,b,c,d
,,,,
list,1,2,3,4
我希望它如下所示:
dict, list
a,1
b,2
c,3
d,4
代码是:
##Opening my dictionary .cvs file
with open('some_file.csv', mode='r') as infile:
reader = csv.reader(infile,)
DICT = {rows[0]:rows[1] for rows in reader if len(rows) == 2}
##Opening my enquiry list .cvs file
datafile = open(self.filename, 'r')
datareader = csv.reader(datafile)
n1 = []
for row in datareader:
n1.append(row)
n = list(itertools.chain(*n1))
headings = ['dict', 'list']
##Writing to .cvs file
with open(asksaveasfilename(), 'w') as fp:
a = csv.writer(fp)
# write row of header names
a.writerow(n)
# build up a list of the values in DICT corresponding to the keys in n
values = []
for name in n:
if name in DICT:
values.append(DICT[name])
else:
values.append("Not Available")
# now write them out
a.writerow(values)
我尝试使用writerows
,但这也会打印错误的数据
d,i,c,t
a
b
c
d
l,i,s,t
1
2
3
4
解决方案:
for nameValueTuple in zip(n,values):
a.writerow(nameValueTuple)
做到了