在csv文件中编写字典:添加列名

时间:2019-04-24 18:17:38

标签: python csv dictionary

我想添加标题,然后为第一列添加键,为第二列添加值

我该怎么做,我尝试过:

d = {}

with open(sys.argv[1], 'r', encoding='utf-8') as csv_file:
    csv_file.readline()
    for line in csv_file:
        token = line.split(';')
        try:
            d[token[0]] = token[1]
        except:
            print(line)
#print(d)


CSV ="\n".join([k+';'+v for k,v in d.items()])
w=csv.DictWriter(open("sortie.csv", "w"), fieldnames =["clé","verbatim","tag","lemme","scorePos","scoreNeu","scoreNeg"],delimiter = ';') 
w.writeheader() 
w.writerow(CSV) 

结果是:


import TreeTagger OK
Traceback (most recent call last):
  File "CSV_dico.py", line 47, in <module>
    w.writerow(CSV)
  File "C:\Users\Emmanuelle\AppData\Local\Programs\Python\Python37-32\lib\csv.py", line 155, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
  File "C:\Users\Emmanuelle\AppData\Local\Programs\Python\Python37-32\lib\csv.py", line 148, in _dict_to_list
    wrong_fields = rowdict.keys() - self.fieldnames
AttributeError: 'str' object has no attribute 'keys'

1 个答案:

答案 0 :(得分:1)

看看DictWriter是如何期待其输入的。您正在尝试将整个CSV作为一行传递给它。

实际上,由于您已经生成了整个CSV,因此您可以手动编写标题,然后手动编写行:

with open("sortie.csv", "w") as output:
    output.write("clé;verbatim;tag;lemme;scorePos;scoreNeu;scoreNeg\n")
    output.write(CSV)