gpt4 book ai didi

python - 无法在 python 2.7 和 django 1.9 中打开具有变音符号的文件名

转载 作者:太空宇宙 更新时间:2023-11-04 10:07:44 25 4
gpt4 key购买 nike

我正在尝试做一个遍历目录中的每个文件的事情,但每次遇到名称中包含元音变音的文件时它都会崩溃。喜欢 ä.txt

缩短的代码:

import codecs
import os

for filename in os.listdir(WATCH_DIRECTORY):
with codecs.open(filename, 'rb', 'utf-8') as rawdata:
data = rawdata.readline()
# ...

然后我明白了:

IOError: [Errno 2] No such file or directory: '\xc3\xa4.txt'

我尝试使用 .encode('utf-8')、.decode('utf-8') 和两者结合对文件名变量进行编码/解码。这通常会导致“ascii 无法解码等等”

我也尝试过使用和不使用编码/解码的 unicode(filename)。

太棒了,有点卡在这里:)

最佳答案

您正在打开一个相对目录,您需要将它们设置为绝对目录。

这与编码无关; Unicode 字符串和字节字符串都可以工作,尤其是从 os.listdir() 中提取时。

但是,os.listdir() 只生成基本文件名,而不是路径,因此请将其重新添加到:

for filename in os.listdir(WATCH_DIRECTORY):
fullpath = os.path.join(WATCH_DIRECTORY, filename)
with codecs.open(fullpath, 'rb', 'utf-8') as rawdata:

顺便说一下,我建议你使用 io.open() function而不是 codecs.open()io 模块是新的 Python 3 I/O 框架,比旧的 codecs 模块更健壮。

关于python - 无法在 python 2.7 和 django 1.9 中打开具有变音符号的文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40023476/

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