将unicode字符从os.walk传递给打印功能

时间:2015-03-14 10:41:33

标签: python python-3.x unicode

我正在尝试在Python 3.4中创建一个简单的文件索引实用程序。目标是使用索引快速搜索文件名。

为此,我使用了os.walk函数,但在尝试打印目录名时遇到了UnicodeEncodeError。我查看了其他问题,例如thisthis,但它们似乎没有描述相同的错误(UnicodeEncodeError)。

我的代码是:

def index_files(path_to_index):
    indexed_files = []

    for dirname, dirnames, filenames in os.walk(path_to_index):
        # print path to all subdirectories first.
        for subdirname in dirnames:
            print(os.path.join(dirname, subdirname))

        # print path to all filenames.
        for filename in filenames:
            full_path = os.path.join(dirname, filename)
            print("Found " + full_path)
            indexed_files.append(full_path)

我得到的输出是:

Traceback (most recent call last):
  File "[OMITTED LOCAL PATH]indexer.py", line 40, in <module>
    main()
  File "[OMITTED LOCAL PATH]indexer.py", line 37, in main
    indexed_files = index_files(path_to_index)
  File "[OMITTED LOCAL PATH]indexer.py", line 16, in index_files
    print(os.path.join(dirname, subdirname))
  File "C:\Python34\lib\encodings\cp850.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 31-34: character maps to <undefined>

这样做的正确方法是什么?

0 个答案:

没有答案