【问题标题】:Opening files in a directory with python, trouble with encoding用python打开目录中的文件,编码问题
【发布时间】:2012-04-19 04:46:38
【问题描述】:
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,但是当它试图打开它时我无法收到此错误

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。怎么了?

【问题讨论】:

    标签: python file encoding operating-system directory


    【解决方案1】:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-23
      • 1970-01-01
      • 1970-01-01
      • 2014-11-21
      • 1970-01-01
      • 1970-01-01
      • 2014-02-16
      • 1970-01-01
      相关资源
      最近更新 更多