2

I've looked at the posts here and here. But they have either been trying to write bytes to a CSV or saving a CSV from a string but I'm trying to connect trying writing bytes to a CSV.

I have a blob of bytes and if I do type(bytes) I get <class 'bytes'> but when I try to write to a csv I get an error

(Pdb) f = open('/Users/minhmai/test.csv', 'wb+')
(Pdb) writer = csv.writer(f)
(Pdb) writer.writerow(bytes)
*** TypeError: a bytes-like object is required, not 'str'


(Pdb) f = open('/Users/minhmai/test.csv', 'wb+')
(Pdb) writer = csv.writer(f)
(Pdb) writer.writerows(bytes)
*** _csv.Error: iterable expected, not int

However If I do this, I just get a number but it's not really saved to a CSV.

(Pdb) wfile = io.StringIO()
(Pdb) writer = csv.writer(wfile)
(Pdb) writer.writerow(bytes)

And example of what my data(bytes) look like is this

b'Date,ID,Amount\r\n2018-1-1,1,25\r\n2018-1-2,2,3\r\n2018-1-1,2,3\r\n`

Ideally this would result in a header row and 3 rows

Minh
  • 2,180
  • 5
  • 23
  • 50
  • 2
    Looks like you overwrote the standard class name `bytes` with some value. Do you have a line `bytes=...` somewhere in your program? Change the variable name to something else! – DYZ Jan 12 '18 at 22:38
  • 1
    Either lose the `b` (*binary* - which makes the content - raw bytes) from `wb+` when opening files, either use `.encode()` when writing strings. – CristiFati Jan 12 '18 at 22:39
  • 2
    In Python 3 `csv.writer` expects a file (like) object opened in *text mode*, with `newline=''`. Your `TypeError` is a result of not honouring that; though you'd try and pass a list of `bytes()` objects, you'd get a *string* row that contained string representations of those objects (the `b'...'` representation). – Ilja Everilä Jan 12 '18 at 22:42
  • I think @Ilja Everilä is exactli right—sounds like the cause and the way to fix the issue. – martineau Jan 12 '18 at 22:52
  • Hey @DYZ. the `bytes` was just an example, in my work, it is named something else but the error is the same @IljaEverilä I've tried doing what you did but it turns out to be a row full of numbers? – Minh Jan 12 '18 at 22:55
  • That we cannot help you with, since you've not provided a [mcve]. – Ilja Everilä Jan 12 '18 at 22:56
  • @IljaEverilä updated. I have created a test snippet. – Minh Jan 12 '18 at 23:02
  • That's a bit confusing. From the looks of it your "snippet" is a bytes object that contains encoded csv text already. Why are you trying to pass that to a writer? – Ilja Everilä Jan 13 '18 at 11:27

0 Answers0