Python os.walk 支持 Unicode/UTF-8?

标签 python python-2.7 unicode encoding utf-8

我已经研究过这个问题,似乎Python 2.7默认使用的是ASCII,由于库的原因我无法切换到python 3(默认Unicode)

# -*- 编码:utf-8 -*- 打印你'порядке'

似乎打印得很好,如果没有 u 则为 ?????? 但: print list(os.walk(ur'c:\somefoler')) 返回 \u0438\u0442... 为什么第一次打印时不可读?另外,我将 os.walk 与变量一起使用,我不能将它与 ur 一起使用,我只是想了解如何使我的以下代码与我使用 os.walk + 的任何文件夹/文件语言一起使用保存到文件似乎都不起作用 ?????? where Cyrillic

def findit(self,root, exclude_files=[], exclude_dirs=[]):
    exclude_files = (fnmatch.translate(i) for i in exclude_files)
    exclude_files = '('+')|('.join(exclude_files)+')'
    exclude_files = re.compile(exclude_files)
    exclude_dirs = (os.path.normpath(i) for i in exclude_dirs)
    exclude_dirs = (os.path.normcase(i) for i in exclude_dirs)
    exclude_dirs = set(exclude_dirs)
    for root, dirs, files in os.walk(root):
        if os.path.normpath(os.path.normcase(root)) in exclude_dirs:
            # exclude this dir and subdirectories
            dirs[:] = []
            continue
        for f in files:
            if not exclude_files.match(os.path.normcase(f)):
                yield os.path.join(root, f)

filelist = list(findit('c:\\',exclude_files = ['*.dll', '*.dat', '*.log', '*.exe'], except_dirs = [ 'c:/windows', 'c:/程序文件', 'c:/else']))

当它是一个变量时,我似乎必须使用.decode('utf-8')?为什么不使用像 u'var' 这样的 unicode(如果存在的话)以及为什么有很多次无法转换的异常遇到它并看到很多带有此类错误的答案我很难理解难道就没有办法让它正常工作吗?

最佳答案

尝试

root = ur'c:\somefoler'
for current,dirs,files in os.walk(root):
    for file in files:
        print file, repr(file)

您应该看到正确的内容(沿着列表中使用的 repr 旁边)...问题是,当您打印列表时,它会打印其项目的 repr

关于Python os.walk 支持 Unicode/UTF-8?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25254063/

相关文章:

python - 在对象定义中使用 "()"和不使用它有什么区别?

python - 从 Python 2.7 中的 args/kwargs 和函数签名填充默认缺失/参数

python - ipython笔记本中的Unicode

php - 如何在 PHP 中打开名称中包含 unicode 字符的文件?

unicode - UTF-8、UTF-16 和 UTF-32 可以存储的字符数是否不同?

python - 我如何使用 sklearn DictVectorizer 对列表进行矢量化

python - df1 中不在 df2 中的所有行

python - 检查对象属性名称是否出现在字符串python中

python - 将注释框添加到 matplotlib 等高线/热图图

python - 有没有办法将当前作用域中的所有变量作为上下文传递给 Mako?