0

I am new to python. I got this pre written code that downloads data in to report. But I am getting the error

"write() argument must be str, not bytes".

See below code

def _download_report(service, response, ostream):

    logger.info('Downloading keyword report')
    written_header = False
    for fragment in range(len(response.files)):
      file_request = service.reports().getFile(
        reportId=response.id_, reportFragment=fragment)
      istream = io.BytesIO(file_request.execute())

    if written_header:
      istream.readline()
    else:
      written_header = True
    ostream.write(istream.read())

3 Answers 3

1

you'll need to change the last line to

ostream.write(istream.read().decode('utf-8'))

PS. you may need to replace `'utf-8`` with whatever encoding the data is in

Sign up to request clarification or add additional context in comments.

Comments

0

To elaborate more on @sgDysregulation's answer:

One peculiarity with python 3 is that strings ('hello, world') and binary strings (b'hello, world') are basically incompatible. As an example, if you're familiar with basic file I/O, there are two types of modes to read a file in - you could use open('file.txt', 'r'), which returns unicode strings when you read from the file, or open('file,txt', 'rb'), which returns binary strings. The same applies for writing - you can't write strings correctly in mode 'wb', and can't write binary strings in mode 'w'.

In this case, your istream returns binary strings when read from, whereas your ostream expects to write a unicode string. The solution is to change encoding from one to the other, and do what sgDysregulation recommends:

ostream.write(istream.read().decode('utf-8'))

this assumes that the binary string is encoded in utf-8 format, which it probably is. You might have to use a different format otherwise.

Comments

0

You have to decode the BytesIO object to get a string that can be written to the file:

ostream.write(istream.read().decode('utf-8'))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.