2012-04-05 44 views
4
import os 
listing = os.listdir(path) 
for infile in listing: 
    print infile 
    f = open(os.path.join(path, infile), 'r') 

我在python中创建了一个脚本,它遍历目录中的所有文件并打开它们。它工作正常,问题出现在一些文件的名称。该文件的名称是Trade_Map _-_List_of_products_exported_by_Côte_d'Ivoire,但是当它试图打开它,我不能让这个错误使用python打开目录中的文件,遇到编码问题

IOError: [Errno 2] No such file or directory: "C:\\Users\\Borut\\Downloads\\GC downloads\\izvoz\\Trade_Map_-_List_of_products_exported_by_Co^te_d'Ivoire.txt"

实名具有Côte_d'Ivoire到底,而我的名字时得到我遍历listdir最后有Co^te_d'Ivoire。哪里不对??

回答

2

os.listdir(path)的编码取决于字符串path的编码。 如果path是unicode,那么os.listdir(path)返回的条目列表将是unicode。否则,返回的列表将使用系统默认编码。如果你想以确保输出文件的列表正确,你可以尝试以下的(未经测试):

import os 
import sys 

path = unicode(path, sys.getfilesystemencoding()) 

# All elements of listing will be in unicode. 
listing = os.listdir(path) 
for infile in listing: 
    print infile 

    # When infile is in unicode, the system to open 
    # the file using the correct encoding for the filename 
    f = open(os.path.join(path, infile), 'r') 

sys.getfilesystemencoding()是让你的系统默认编码的方法,这是多么open等方法希望自己的字符串输入(即使unicode也很好,因为它们会自动将它们转换为默认编码)。

参考:http://docs.python.org/howto/unicode.html#unicode-filenames