简体   繁体   中英

Printing a counter to csv file in Python error

I seem to be having an issue with printing a counter to csv file. I've tried following the threads Python: Writing Counter to a csv file , 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' , but it seems I keep stumbling into problems.

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):

   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:

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:

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. It should always be safe to specify newline=”, since the csv module does its own (universal) newline handling.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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