Python 将以下词典列表转换为csv文件

Python 将以下词典列表转换为csv文件,python,python-3.x,csv,command-line,file-handling,Python,Python 3.x,Csv,Command Line,File Handling,我有一个这样的字典列表,存储在一个名为“sourcetimes.txt”的文本文件中--- 我想将其创建为csv文件,如下所示---- 我编写了以下代码---- 但是,当我尝试执行它时,命令行中会出现以下错误---- C:\Users\Dell\Desktop\googlepython>python logprogram2.py sourcetimes.txt 回溯(最近一次呼叫最后一次): 文件“logprogram2.py”,第15行,在 writer.writerows(源文件) writ

我有一个这样的字典列表,存储在一个名为
“sourcetimes.txt”的文本文件中
---

我想将其创建为csv文件,如下所示----

我编写了以下代码----

但是,当我尝试执行它时,命令行中会出现以下错误----

C:\Users\Dell\Desktop\googlepython>python logprogram2.py sourcetimes.txt
回溯(最近一次呼叫最后一次):
文件“logprogram2.py”,第15行,在
writer.writerows(源文件)
writerows中的文件“C:\Users\Dell\AppData\Local\Programs\Python\37\lib\csv.py”,第158行
返回self.writer.writerows(映射(self.\u dict\u to\u list,rowdicts))
文件“C:\Users\Dell\AppData\Local\Programs\Python\37\lib\csv.py”,第148行,在目录列表中
错误的_fields=rowdict.keys()-self.fieldnames
AttributeError:“str”对象没有属性“keys”

我应该怎么做才能更正它呢?

您得到错误是因为
sys.argv[1]
返回一个字符串,而
writer.writerows()
只接受字典作为参数。

您得到错误是因为
sys.argv[1]
返回一个字符串,而
writer.writerows()
仅将字典作为参数。

这是否回答了您的问题?这回答了你的问题吗?
> [{'Microsoft-Windows-DistributedCOM': 5355,
> 'Microsoft-Windows-Kernel-General': 6717,
> 'Microsoft-Windows-Winlogon': 1045}]
    **source**                              **times**
    Microsoft-Windows-DistributedCOM          5355
    Microsoft-Windows-Kernel-General          6717
    Microsoft-Windows-Winlogon                1045    
#this program converts data stored in "sourcetimes.txt" into a csv file
#the output is stored in "sourcetimes2.csv"

import csv
import os
import sys

sourcefile=sys.argv[1]

keys=["source","times"]

with open("sourcetimes2.csv","w") as file:
    writer=csv.DictWriter(file,fieldnames=keys)
    writer.writeheader()
    writer.writerows(sourcefile)
C:\Users\Dell\Desktop\googlepython>python logprogram2.py sourcetimes.txt
Traceback (most recent call last):
  File "logprogram2.py", line 15, in <module>
    writer.writerows(sourcefile)
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python37\lib\csv.py", line 158, in writerows
    return self.writer.writerows(map(self._dict_to_list, rowdicts))
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python37\lib\csv.py", line 148, in _dict_to_list
    wrong_fields = rowdict.keys() - self.fieldnames
AttributeError: 'str' object has no attribute 'keys'