在 Python 错误中打印 csv 文件的计数器

Printing a counter to csv file in Python error

我似乎在将计数器打印到 csv 文件时遇到了问题。我已经尝试关注线程 , How do you write a counter to a file in order?, and Python: Writing a dictionary to a csv file with one line for every 'key: value',但似乎我总是遇到问题。

我的计数器格式如下:

>>> print(daysCounter)
Counter({'03/08/2016': 246, '13/12/2016': 220, '22/01/2016': 198, '20/09/2016': 191})

计数器要大得多,但这提供了格式化思路。

现在,当我尝试使用(之前导入了 csv)时:

   with open('lifetime_edits.csv', 'wb') as csv_file:
        writer = csv.writer(csv_file)
        for key, value in daysCounter.items():
            writer.writerow([key, value])

我收到错误:

Traceback (most recent call last):
  File "contribs.py", line 138, in <module>
    lifetime_analysis(data)
  File "contribs.py", line 91, in lifetime_analysis
    writer.writerow([key, value])
TypeError: a bytes-like object is required, not 'str'

所以我假设我只是没有正确使用某些东西,并且完全无法理解正在发生的事情。如果有人能对我为什么会遇到这个问题以及如何解决它发表一些见解,我将不胜感激。

请注意,此操作的最终目标是让上述计数器打印到以下格式的文件中:

03/08/2016,246
13/12/2016,220
22/01/2016,198
20/09/2016,191

非常感谢您的关注和时间。

with open('lifetime_edits.csv', 'wb') as csv_file:

这需要一个字节输入,你用'b'模式打开文件,就用'w'模式,这个模式默认输入是str:

with open('lifetime_edits.csv', 'w') as csv_file:

推荐方式:

with open('lifetime_edits.csv', 'w', newline='') as csv_file:

If newline=” is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \r\n linendings on write an extra \r will be added. It should always be safe to specify newline=”, since the csv module does its own (universal) newline handling.