首页 > 解决方案 > os.walk() 在 Windows 10 上为带有重音字母的文件生成无效路径

问题描述

我正在尝试运行一个返回文件夹总大小及其所有内容的函数。这是功能:

#!/usr/local/bin/python
# -*- coding: utf-8-*-

import os


def get_size(start_path = '.'):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            # skip if it is symbolic link
            if not os.path.islink(fp):
                total_size += os.path.getsize(fp)

    return total_size

该函数适用于任何路径作为输入,除非我给它一个文件夹的路径,该文件夹的名称上有一个带有重音字母的文件。

我收到此错误:

Traceback (most recent call last):
  File "C:/Users/Owner/PycharmProjects/test/tester.py", line 18, in <module>
    print get_size("c:\\nizan\\kal")
  File "C:/Users/Owner/PycharmProjects/test/tester.py", line 13, in get_size
    total_size += os.path.getsize(fp)
  File "C:\Python27\lib\genericpath.py", line 49, in getsize
    return os.stat(filename).st_size
WindowsError: [Error 123] The filename, directory name, or volume label  
syntax is incorrect: 'c:\\nizan\\kal\\?xample.txt'

Process finished with exit code 1

导致问题的文件的真实名称是“éxample.txt”。我尝试过使用此处所示的解码。但它没有用。

标签: pythonpython-2.7windows-10

解决方案


推荐阅读