gpt4 book ai didi

python - 使用python打开目录中的文件,编码有问题

转载 作者:太空宇宙 更新时间:2023-11-03 11:34:00 25 4
gpt4 key购买 nike

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] 没有这样的文件或目录:“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。怎么了??

最佳答案

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

关于python - 使用python打开目录中的文件,编码有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10028704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com