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

问题描述:

我似乎遇到打印计数器到csv文件的问题。我试过了线程Python: Writing Counter to a csv fileHow do you write a counter to a file in order?Python: Writing a dictionary to a csv file with one line for every 'key: value',但似乎我一直在陷入问题。在Python错误中打印csv文件的计数器

我有反格式化,像这样:

>>> 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.

+0

nnnnngggghhhhhh,是的,这解决了这个问题。谢谢你澄清它。 我不确定它是否相关,但似乎在这个csv文件中每行之间都有一条空行。这是正常的行为吗? – Ronan

+0

该代码工作正常,我不知道是一个系统问题,但在文档中,有一个安全的方法来做到这一点,我更新了代码 –

+0

真棒,那加法摆脱了换行符。下次我会保持这种状态。感谢您的时间! – Ronan