gpt4 book ai didi

python - 在 Python 中处理 UTF 文件名

转载 作者:可可西里 更新时间:2023-11-01 14:13:55 25 4
gpt4 key购买 nike

我已经阅读了很多关于该主题的内容,包括此处似乎是该主题的权威指南:http://docs.python.org/howto/unicode.html

也许对于更有经验的开发人员来说,该指南可能就足够了。但是,就我而言,我比开始时更加困惑,但仍未解决我的问题。

我正在尝试使用 os.walk() 读取文件名,并在将该信息写入文本文件之前获取有关文件的某些信息(例如文件大小)。只要我没有遇到任何文件名以 utf 编码的文件,它就可以工作。当它遇到一个带有 utf 编码名称的文件时,我会收到类似这样的错误:

WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: 'Documents\\??.txt'

在那种情况下,文件被命名为唽咿.txt。

到目前为止,我一直在尝试这样做:

for (root, dirs, files) in os.walk(dirpath):
for filename in files:
filepath = os.path.join(root, filename)
filesize = os.stat(filepath).st_size
file = open(filepath, 'rb')
stuff = get_stuff(filesize, file)
file.close()

万一重要,dirpath 来自代码的较早部分,相当于“dirpath = raw_input()”。

我尝试了各种方法,例如将文件路径行更改为:

filepath = unicode(os.path.join(unicode(root), unicode(filename)))

但我尝试过的都没有用。

这是我的两个问题:

  1. 如何让它将正确的文件名传递给 os.stat() 方法,以便从中获得正确的响应?

  2. 我的脚本需要将一些文件名写入文本文件,稍后可能需要从中读取。那时它需要能够根据刚刚从文本文件中读取的内容找到文件。如何将此类文件名正确写入文本文件,然后再从中正确读取?

最佳答案

unicode 路径传递给 os.walk()

Changed in version 2.3: On Windows NT/2k/XP and Unix, if path is a Unicode object, the result will be a list of Unicode objects.

source

关于python - 在 Python 中处理 UTF 文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11545185/

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