【问题标题】:UTF-8 and os.listdir()UTF-8 和 os.listdir()
【发布时间】:2014-12-31 05:10:31
【问题描述】:

我在处理包含“ș”字符(UTF-8 中的 \xC8\x99 - 下方带有逗号的拉丁小写字母 S)的文件时遇到了一些问题。

我正在创建一个ș.txt 文件并尝试使用os.listdir() 将其取回。不幸的是,os.listdir() 将其返回为s\xCC\xA6 ("s" + COMBINING COMMA BELOW),我的测试程序(如下)失败。

这发生在我的 OS X 上,但它适用于 Linux 机器。知道究竟是什么导致了这种行为(两个环境都配置了 LANG=en_US.UTF8)?

这是测试程序:

#coding: utf-8
import os

fname = "ș.txt"
with open(fname, "w") as f:
    f.write("hi")

files = os.listdir(".")
print "fname: ", fname
print "files: ", files

if fname in files:
    print "found"
else:
    print "not found"

【问题讨论】:

    标签: python linux macos utf-8


    【解决方案1】:

    OS X filesystem mostly uses decomposed characters 而不是它们的组合形式。您需要将文件名规范化回 NFC 组合规范化形式:

    import unicodedata
    files = [unicodedata.normalize('NFC', f) for f in os.listdir(u'.')]
    

    这会将文件名处理为 unicode;否则,您需要先将字节串解码为 un​​icode。

    另见unicodedata.normalize() function documentation

    【讨论】:

    • 感谢您的链接,我明白现在发生了什么。顺便说一句,您的代码不起作用,我需要改为 u"ș.txt" in [unicodedate.normalize('NFC', f) for f in os.listdir(u'.')]
    • @Unknown:对,或者解码再编码。但是使用 unicode 路径更好。
    • @Unknown 你怎么能做到这一点?我也面临这个问题
    • @NamPham:具体做什么,你面临什么问题? files 列表将包含一个 Unicode 字符串对象列表,每个对象都经过规范化。
    • 我正面临解码和编码过程,我不能把u'.' 作为listdir 的参数。我的路径是 unicode :(
    猜你喜欢
    • 2020-12-09
    • 2017-05-07
    • 1970-01-01
    • 2011-10-11
    • 2017-05-19
    • 2015-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多