Marx Babu
Marx Babu

Reputation: 760

Python 2.x to 3.x converted code fails in IO.StringIO conversion

python 2.x code

sdata = StringIO.StringIO(c.data)

python 3.x code

sdata = io.StringIO(c.data)

complete code

def downloadCSV(c, d):
    filename = c.getFilename(d)
    reqstr = c.getReqStr(d)

    print(("Downloading %s ..." % (filename)))
    if c.getResponse(reqstr) == -1:
        return -1
    sdata = io.StringIO(c.data)
    z = zipfile.ZipFile(sdata)

Error :

Traceback (most recent call last):
  File "xxx.py", line 166, in <module>
    main(sys.argv[1:])
  File "xxxx.py", line 158, in main
    getMonth(c, args[1], args[2])
  File "xxxx.py", line 133, in getMonth
    if downloadCSV(c, d) > -1:
  File "xxxx.py", line 73, in downloadCSV
    sdata = io.StringIO(c.data)
TypeError: initial_value must be str or None, not bytes

right import is done for 3.x python version and the conversion for sdata should be automatically happening here ? Why this above error coming ,and what is the way to correct this error in python3.x . Tried other answers posted in this forum but nothing seeming to be working in this case.

Upvotes: 1

Views: 1041

Answers (1)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140246

Python 3 now makes a difference between str and bytes.

Your request returned binary data, so to be able to store it in a io object you have to create a BytesIO object not a StringIO object. So:

sdata = io.BytesIO(c.data) 

Note that the code is still compatible with Python 2.

Upvotes: 2

Related Questions