【问题标题】:Python os.walk Make It Support Unicode/UTF-8?Python os.walk 让它支持 Unicode/UTF-8?
【发布时间】:2014-10-04 22:02:09
【问题描述】:

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

# -*- coding: utf-8 -*- print u'порядке'

似乎打印得很好,如果没有u,它将是?????? 但: print list(os.walk(ur'c:\somefoler')) 返回 \u0438\u0442... 为什么第一次打印不可读?此外,我将 os.walk 与变量一起使用,我无法将其与 ur 一起使用不要总是工作???? 西里尔文

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'], exclude_dirs = ['c:/windows', 'c:/program files', 'c:/else']))

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

【问题讨论】:

    标签: python python-2.7 unicode encoding utf-8


    【解决方案1】:

    试试

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

    您应该看到正确的东西(与列表中使用的 repr 一起)...问题是当您打印列表时,它会打印其项目的 repr

    【讨论】:

    • 这会起作用,但正如你所看到的,我有os.walk(root) 不能做urroot 我能找到的替代方案是.decode('utf-8')(需要仔细检查root 是unicode 之前?)但就我在不同的答案中看到的而言,在所有情况下工作似乎并不可靠,所以我只是不明白应该如何正确地做到这一点
    • 啊是的,我可以在list(findit('c:\\' 上更改它ur 将始终有效?文件怎么样,这只是 dirs 文件,我不能像这样简单地更改它
    • os.walk 也有子目录,我还需要用 ur 对它们进行 unicode 一些文件是的,我可以按照你的建议并用 ur 更改根目录,但子类别和文件仍然会是 ASCII 编码而不是 unicode
    • 如果我使用 unicode 字符串作为根目录,我会得到 <type 'unicode'> 文件。
    猜你喜欢
    • 1970-01-01
    • 2010-12-23
    • 2016-05-03
    • 2018-08-07
    • 1970-01-01
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 2010-10-05
    相关资源
    最近更新 更多