【问题标题】:Python - "The system cannot find the file specified" due to special character in filenamePython - 由于文件名中的特殊字符,“系统找不到指定的文件”
【发布时间】:2017-12-11 03:32:06
【问题描述】:

作为我的 python 脚本的一部分,我正在测试两个文件的大小是否相同:

os.path.getsize(dir_file) # dir_file = root path + filename joined

但是当我遇到一个文件名中包含一些特殊字符(例如 Ü)时,我收到以下错误:WindowsError: [Error 2] The system cannot find the file specified\xf6 之类的东西替换了特殊字符。

我尝试将dir_file 编码为 utf-8,如下所示:

unicode(dir_file, 'utf-8') # method 1
dir_file.encode('utf-8') # method 2

但这给了我以下错误:UnicodeDecodeError: 'ascii' codec can't decode byte 0xf6 in position 79: ordinal not in range(128)

不知道如何解决这个字符编码问题。

【问题讨论】:

  • 我们可以猜到,但您应该在标签中指定您的 Python 版本。 Python 2 和 Python 3 处理 Unicode 的方式非常不同。
  • 你是如何初始化和加入变量 dir_file 的内容的?
  • @RoryDaulton 哦,好的。我正在使用 Python 2
  • @anneb os.path.join(root, filename)
  • 请参阅stackoverflow.com/q/11545185,但在这些情况下也可以考虑切换到 Python 3:PEP 519helps

标签: python string unicode ascii python-2.x


【解决方案1】:

尝试使用sys.getfilesystemencoding() 获取文件系统的编码以阐明您的需求。

然后确保你传入参数的字符串使用相同的编码

if isinstance(dir_file, str):
 print "ascii"
elif isinstance(dir_file, unicode):
 print "unicode"

给出你的结果,我会更新答案。

【讨论】:

  • 当我将根目录字符串解码为unicode,然后将其输入os.walk() 时,它可以正常工作。但是,当我在大量文件上测试脚本时,每 1000 个文件中约有 1 个会生成 IOError(当我尝试打开它时)或 UnicodeEncodeError(当我尝试打印目录时)。我跑了sys.getfilesystemencoding(),结果得到了“mbcs”(如果有帮助的话)
  • UnicodeEncodeError 已通过在打印之前将字符串编码为 utf-8 来解决。 IOError 仍然让我无法理解
猜你喜欢
  • 2013-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-08
  • 2019-08-03
  • 2014-03-16
  • 1970-01-01
相关资源
最近更新 更多