Some Pyhon 2 To Python 3 Tips

August 24, 2017

A few thoughts having just tweaked a script to run under Python 3.

The newer print() function syntax works in both 2 and 3. You most likely have print "" statements in your Python 2 script. Update to the new syntax and you'll be able to work in both 2 and 3.

The write statement in the following block throws and error in 3 unless you open the file in binary mode. The following block is the updated one from my script and it runs in 2 and 3.

    with open (filename, 'wb') as handle:
        for block in response.iter_content(1024):
            handle.write(block)

I was processing the content retrieved from a web page using the requests library. In 2 it worked fine as follows:

    lines = r.content.strip().replace('}', '\n')

Under 3 I received this error:

TypeError: a bytes-like object is required, not 'str'

The fix is to decode the content before proc3essing it as follows. This block works in 2 and 3.

    lines = r.content.decode('unicode-escape').strip(). replace('}', '\n')

Tags: python