【问题标题】:Handling UTF filenames in Windows在 Windows 中处理 UTF 文件名
【发布时间】:2014-07-15 19:32:17
【问题描述】:

给定以下文件:

E:/媒体/Foo/info.nfo E:/媒体/酒吧/FXGâ¢.nfo

我可以通过以下方式“找到”它们:

BASE = r'E:/Media/'

for dirpath, _, files in os.walk(BASE):
    for f in fnmatch.filter(files, '*.nfo'):
        nfopath = os.path.join(dirpath, f)
        print(nfopath)

然后这个 sn-p 将打印上述路径。

但是,如果我确保由 os.path.join() 创建的每个路径确实是一个常规文件——例如:

for dirpath, _, files in os.walk(BASE):
    for f in fnmatch.filter(files, '*.nfo'):
        nfopath = os.path.join(dirpath, f)
        print(nfopath)
        assert os.path.isfile(nfopath)   # <------

第二个文件名的断言失败,但第一个文件名失败。

我在资源管理器中检查了文件夹,脚本确实找到了一个常规文件并正确打印了名称和路径,所以我不清楚断言失败的原因。

我尝试将 BASE 字符串指定为 unicode 字符串 (ur'E:/Media/'),并在 isfile() 调用 (assert os.path.isfile(nfopath.encode('utf-8'))) 中显式编码 nfopath

似乎都不起作用。

当然,我可以跟踪并手动检查并删除失败的文件,但我对如何正确处理这一点很感兴趣。

提前致谢。

(Python 2.7,Windows 7)

【问题讨论】:

  • 我不能肯定地告诉你,但是文件 API 在 3.x 中被重新设计,以便在 Windows 中更好地处理 unicode。可以试试 3.x 吗?
  • 尝试打印repr(nfopath),看看是否能有所启发。

标签: python python-2.7 filenames windows-7-x64 utf


【解决方案1】:

根据this SO question,Windows 在使用 NTFS 文件系统时将文件名存储为 UTF-16。使用 UTF-16 重试您的编码步骤。

【讨论】:

    猜你喜欢
    • 2011-11-07
    • 2011-02-23
    • 1970-01-01
    • 2012-12-10
    • 1970-01-01
    • 2016-02-24
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多