2017-07-06 90 views
1

特殊字符作为我的python脚本的一部分,我测试,看看这两个文件使用相同的尺寸:Python的 - “系统找不到指定文件”由于文件名

os.path.getsize(dir_file) # dir_file = root path + filename joined 

但当我遇到一个名称中包含特殊字符的文件时(例如Ü),我得到以下错误:WindowsError: [Error 2] The system cannot find the file specified替换为特殊字符\xf6

我已经试过编码dir_file为UTF-8,像这样:

unicode(dir_file, 'utf-8') # method 1 
dir_file.encode('utf-8') # method 2 

但是,这使我有以下错误:UnicodeDecodeError: 'ascii' codec can't decode byte 0xf6 in position 79: ordinal not in range(128)

不知道如何解决这个字符编码问题。

+2

我们可以猜到,但是您应该在标签中指定您的Python版本。 Python 2和Python 3处理Unicode的方式非常不同。 –

+0

你是如何初始化和准确加入变量dir_file的内容的? – anneb

+1

@RoryDaulton哦,好的。我使用Python 2 – sookie

回答

1

尝试使用sys.getfilesystemencoding()来获得文件系统的编码以阐明您的需求。

然后,确保您在参数传递的字符串使用相同的编码

if isinstance(dir_file, str): 
print "ascii" 
elif isinstance(dir_file, unicode): 
print "unicode" 

给你的结果,我会更新的答案。

+0

当我在将根目录字符串输入到'os.walk()'之前解码为“unicode”时,我使用它。但是,当我在大量文件上测试脚本时,每1000个文件中大约有1个文件会产生'IOError'(当我尝试打开它时)或'UnicodeEncodeError'(当我尝试打印目录时)。我运行了'sys.getfilesystemencoding()'并得到了'mbcs'作为结果(如果有帮助) – sookie

+0

在打印之前,通过将字符串编码为utf-8解决了'UnicodeEncodeError'问题。 'IOError'仍然没有我 – sookie

相关问题