2

DictWriter 似乎对我不起作用。

当前代码:

myfile = open('hashdict.csv', 'wb')
fieldnames = ('md5', 'value')
myWriter = csv.DictWriter(myfile, fieldnames=fieldnames)
headers = dict((n,n) for n in fieldnames)
myWriter.writerow(headers)
for n in dictToSearch:
    myWriter.writerow(n)
myfile.close()

追溯:

Traceback (most recent call last):
  File "hash.py", line 42, in <module>
    myWriter.writerow(n)
  File "C:\Python27\lib\csv.py", line 148, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
  File "C:\Python27\lib\csv.py", line 144, in _dict_to_list
    ", ".join(wrong_fields))
ValueError: dict contains fields not in fieldnames: d, 1, a, 5, 0, d, 0, a, 1, 7
, 0, e, 5, e, a, 9, f, e, b, 6, f, 7, 9, 6, 1, 3, 6, 3, f, 6, d, 9

字母数字字符来自 MD5 哈希,但这就是我能告诉你的全部内容。我查看了文档,似乎无法理解它。我要做的是从名为 dictToSearch 的字典中创建一个 CSV 文件。

提前感谢您的帮助,如果您需要任何其他信息,请告诉我。

完整代码链接:http: //pastebin.com/A3E4AJfV

4

1 回答 1

5

The key missing piece of information here: what is dictToSearch? I guess that it's something like {'e2fc714c4727ee9395f324cd2e7f331f': 'abcd', '098f6bcd4621d373cade4e832627b4f6': 'test'}.

If so, the issue here is that "for n in dictToSearch" sets n to the first key of dictToSearch - which will be an MD5 hash. writerow(n) then interprets that MD5 hash string as a dictionary in its own right consisting of single-character keys and values, not as a string.

I suspect that what you really want to do is:

for key, value in dictToSearch.items():
    myWriter.writerow({'md5' : key, 'value': value})

which converts an entry from dictToSearch into its own dictionary matching the field names you're using.

于 2013-02-03T01:36:20.700 回答