-3

I was wondering if there is a way to get around this error. Any help would be appreciated!

TypeError: can't concat bytes to str
import marshal, imp

f=open('PYTHONSCRIPT','rb')
f.seek(28)  # Skip the header, you have to know the header size beforehand

ob=marshal.load(f)

for i in range(0,len(ob)):
    open(str(i)+'.pyc','wb').write(imp.get_magic() + '\0'*4 + marshal.dumps(ob[i]))

f.close()

open(str(i)+'.pyc','wb').write(imp.get_magic() + '\0'*4 + marshal.dumps(ob[i]))
Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146

2 Answers2

2

'\0'*4 is a str, use b'\0' * 4 to get the needed bytes value.

1

Your problem is that you are trying to concatenate two bytes and a str. This is not possible in python3 because python3 makes a clear distinction between bytes and strings (a good thing given the somewhat fuzzy distinctions between str and unicode in python2). I think what you want is probably the following:

import marshal, imp

f=open('PYTHONSCRIPT','rb')
f.seek(28)  # Skip the header, you have to know the header size beforehand

ob=marshal.load(f)

for i in range(0,len(ob)):
    with open(str(i)+'.pyc','wb') as my_file:
        my_file.write(imp.get_magic() + b'\0'*4 + marshal.dumps(ob[i]))

f.close()

with open(str(i)+'.pyc','wb') as my_file:
    my_file.write(imp.get_magic() + b'\0'*4 + marshal.dumps(ob[i]))

The b before the strings is a marker that tells python that the strings are byte strings instead of str strings.

Note also that I added with ... as ...: which will make sure that your files get deterministically closed right away even in non-CPython implementations (PyPy, Jython, IronPython, etc).

CrazyCasta
  • 26,917
  • 4
  • 45
  • 72