1
votes

I have to re-code a python 2.7 script to python 3.8. I'm having a issue with this type of error:

name = name.replace(char, '_') TypeError: a bytes-like object is required, not 'str'

After trying to find a solution on the internet, I kinda understand that the way python3 encode decode bytes and string is different than python 2.7 however, being still very new to python I tried some of the solutions found but still getting this error.

forbidden_char = ['~', '"', '#', '%', '&', '*', ':',
                      '<', '>', '?', '/', '\\', '{', '|', '}', ',']

print("Sanitizing {} folder...".format(folder))
        for root, dirnames, filenames in os.walk(folder):

            for name in filenames + dirnames:
                original_name = name
                # original_root = root

                if force:
                    name = removeAccentsAndAll(name)
                else:
                    force_rename = False
                    # Only take UTF8 names
                    try:
                        name.decode('utf-8')
                    except:
                        print("  Found non-UTF8 name, re-encoding everything...")
                        name = name.encode('utf-8')
                        # root = root.encode('utf-8')

                # Remove trailing and ending spaces
                if name[0] == ' ':
                    print("  Trailing spaces detected, removing")
                    name = name.lstrip(' ')
                if name[-1] == ' ':
                    print("  Ending spaces detected, removing")
                    name = name.rstrip(' ')

                # Remove all ending points
                if name[-1:] == '.':
                    print("  Ending points detected, removing")
                    name = name.rstrip('.')

                # Remove forbidden char only if we are in blacklist mode
                if not force:
                    for char in forbidden_char:
                        name = name.replace(char, '_')

I'm guessing that the error comes from " '_' " but even if I try to encode it as byte it doesn't work.

Any recommendation ?

Cheers, Xzi.

1
What is name and forbidden_char?DirtyBit
Thanks, I did edit my post giving a bigger sample of the code. Forbidden_char is a list of character that we would like to replace by '_' instead.Vincent Aury
Maybe name.replace(char, b'_') to convert _ to a byte? And also put a b prefix to all the characters in list forbidden_char.qouify
@qouify indeed, it works now. I put the "b" prefix to convert "_" but I didn't do it through every char in forbidden list. Now it is working fine, thanks a lot !Vincent Aury

1 Answers

0
votes

Code fixed by adding "b" suffix to "name.replace(char,b'_') and the list called "forbidden_char".

Xzi.