简体   繁体   English

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

[英]Printing a counter to csv file in Python error

I seem to be having an issue with printing a counter to csv file. 我似乎在将计数器打印到csv文件时遇到问题。 I've tried following the threads Python: Writing Counter to a csv file , How do you write a counter to a file in order? 我已尝试遵循以下线程Python:将Counter写入csv文件如何按顺序向文件写入计数器? , and Python: Writing a dictionary to a csv file with one line for every 'key: value' , but it seems I keep stumbling into problems. Python:将字典写入csv文件,每个'key:value'一行 ,但似乎我一直在陷入困境。

I have the counter formatted like so: 我的计数器格式如下:

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

The counter is much bigger, but this gives the formatting idea. 计数器更大,但这给出了格式化的想法。

Now when I try to use (having imported csv earlier): 现在,当我尝试使用时(之前已导入了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])

I get the error: 我得到错误:

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'

So I am assuming I am simply not using something properly, and am completely failing at understanding what is happening. 因此,我假设我只是没有正确使用某些东西,而完全无法理解正在发生的事情。 If anyone could shed some insight on why I am getting this problem, and if possible how to solve it, I would be very grateful. 如果有人能对我为什么会遇到这个问题以及如何解决这个问题有所了解,我将非常感激。

Note that the end goal of this would be to get the above Counter to print to a file of the format: 请注意,此操作的最终目标是使上面的Counter打印到以下格式的文件:

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

Many thanks for your attention and time. 非常感谢您的关注和时间。

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

this require a bytes input, you open the file with 'b' mode, just use 'w' mode, this mode default input is str: 这需要一个字节输入,您可以使用“ b”模式打开文件,只需使用“ w”模式,此模式的默认输入为str:

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

recommend way: 推荐方式:

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. 如果未指定newline =”,则嵌入引号中的换行符将无法正确解释,并且在使用\\ r \\ n linendings的平台上,将添加一个额外的\\ r。 It should always be safe to specify newline=”, since the csv module does its own (universal) newline handling. 由于csv模块会执行自己的(通用)换行符处理,因此指定newline =”应该总是安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM