Files
Python_CookBook_repo/5.文件与IO/15.打印无法解码的文件名.py
2025-09-10 16:12:45 +08:00

14 lines
560 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

if __name__ == "__main__":
# 有时候,可能会出现一些标准情况下打印会出现问题的文件名,他们不遵循系统的默认编码方式
# 这时候如果print这些文件名那么py会因为无法解码而将字符映射到一个代理编码表显然print无法处理这些代理为空的新建编码
# 解决的方案是建一个转换函数
def bad_filename(filename):
return repr(filename)[1: -1]
name = ''
try:
print(name)
except UnicodeEncodeError:
print(bad_filename(name))