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.
name
andforbidden_char
? – DirtyBitname.replace(char, b'_')
to convert_
to a byte? And also put ab
prefix to all the characters in listforbidden_char
. – qouify