Skip to main content
 首页 » 编程设计

Python os.walk 使其支持 Unicode/UTF-8

2024年10月25日8lvdongjie

我已经研究过这个问题,似乎 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'], exclude_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