0

I've been trying to get this work but getting the error TypeError: a bytes-like object is required, not 'str'' after upgrading to python 3.

What am I doing wrong here? I tried r, wb+ and w learned from here, Confused by python file mode "w+"

my code:

with open(output_filename, 'wb') as f:   
    # write column names
    f.write("stack,overflow,super,user\n")
    writer = csv.writer(f)

Can anyone help with this? Thanks.

excelguy
  • 1,574
  • 6
  • 33
  • 67
  • You're attempting to write a `str`ing to a file opened in `b`inary mode. This doesn't make much sense because you didn't tell Python how to convert your string to bytes, so you're getting the error. – ForceBru Aug 16 '19 at 20:49
  • You could also use `writer.writerow` to write the header, but using `'w'` mode, not `'wb'`. The `+` just means append if the file is already there. Look at the `csv.writer` section of https://docs.python.org/3/library/csv.html – Deepstop Aug 16 '19 at 20:57

1 Answers1

1

The difference between 'wb' and 'w' filemodes is that 'wb' directly reads the binary and 'w' reads it as string. Your issue is that you're using 'wb' instead of 'w'. csv.writer is expecting a string, not binary.

If you use with open(output_filename, 'w') as f: instead, it should work.

anderw
  • 103
  • 3
  • this seems to work! although now when my code writes to csv it skips a line each time! – excelguy Aug 19 '19 at 13:27
  • I don't know what your code is, but python's `csv.writer.writerow` will automatically append a newline at the end. Maybe you're adding an extra newline? – anderw Aug 19 '19 at 16:00