[英]TypeError bytes-like object is required, not str
我必须将 python 2.7 脚本重新编码为 python 3.8。 我遇到此类错误的问题:
name = name.replace(char, '_') TypeError: 需要类似字节的 object,而不是 'str'
尝试在 inte.net 上找到解决方案后,我有点明白 python3 编码解码字节和字符串的方式与 python 2.7 不同,但是,对于 python 来说仍然很新,我尝试了一些找到的解决方案,但仍然出现此错误。
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, '_')
我猜错误来自“'_'”,但即使我尝试将其编码为字节,它也不起作用。
有什么推荐吗?
干杯,Xzi。
通过将“b”后缀添加到“name.replace(char,b'_') 和名为“forbidden_char”的列表来修复代码。
Xzi。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.