我必须将python 2.7脚本重新编码为python 3.8。我遇到此类错误的问题:
name = name.replace(char,'_') TypeError:需要一个类似字节的对象,而不是'str'
尝试在互联网上找到解决方案后,我有点理解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。
答案 0 :(得分:0)
通过在“ name.replace(char,b'_')”和名为“ forbidden_char”的列表中添加“ b”后缀来修复代码。
Xzi。