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

标签 python django python-2.7 encoding utf-8

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

相关文章:

python - celery - 无法获取任务结果

python - 从 View 导入数据后如何将下拉数据分配给字段

python - 在Python中按日期从http下载多个XLS文件

python - 在 cx 卡住中制作 msi - reportlab 中的模块

python - 混合 PostgreSQL 和 MongoDB(作为 Django 后端)

python - 导入错误: No module named SOAPpy

python - 在selenium中单击select2下拉列表时出现问题

python - 在 Jenkins 中发送电子邮件时添加 png 图像和表格 html

python - PyCharm 和 Python 控制台

python - 如何使用 torch.min 中的索引来索引多维张量