1

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.

Community
  • 1
  • 1
Ronan
  • 407
  • 3
  • 5
  • 13

1 Answers1

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

宏杰李
  • 11,820
  • 2
  • 28
  • 35
  • nnnnngggghhhhhh, yeah that solved the problem. Thank you for clarifying it. I'm not sure if it's related, but it seems like in this csv file there is an empty line between each row. Is this normal behavior? – Ronan Dec 14 '16 at 04:04
  • the code works fine, i not sure is that a system problem, but in the document, there is a safe way to do this, i updated the code – 宏杰李 Dec 14 '16 at 04:10
  • Awesome, that addition got rid of the newline. I'll keep that in ind next time. Thank you for your time! – Ronan Dec 14 '16 at 04:13