如何在Python中打开中文文件名的文件

3 投票
5 回答
7432 浏览
提问于 2025-04-16 13:53

我正在尝试用Python中的“open()”函数以“w”模式打开一个文件。

这个文件的名字是:仿宋人笔意.jpg。

使用这个文件名时,打开函数失败,但用普通文件名时却能成功。

我该如何在Python中打开那些不是英文的文件名呢?

我的代码如下:

try:
    filename = urllib.quote(filename.encode('utf-8'))
    destination = open(filename, 'w')
    yield("<br>Obtained the file reference")
except:
    yield("<br>Error while opening the file")

对于非英文文件名,我总是收到“打开文件时出错”的提示。

提前谢谢你们。

5 个回答

4

如果你遇到问题,可能是你的操作系统或终端设置出了问题,而不是Python本身;我在没有使用codecs模块的情况下也能正常工作。

下面是一个测试的命令行记录,它打开了一个图片文件,并把它复制到一个你提供的中文名字的新文件里:

$ ls
create_file_with_chinese_name.py    some_image.png
$ cat create_file_with_chinese_name.py 
#!/usr/bin/python
# -*- coding: UTF-8 -*-

chinese_name_file = open(u'仿宋人笔意.png','wb')

image_data = open('some_image.png', 'rb').read()

chinese_name_file.write(image_data)

chinese_name_file.close()
$ python create_file_with_chinese_name.py 
$ ls
create_file_with_chinese_name.py    some_image.png              仿宋人笔意.png
$ diff some_image.png 仿宋人笔意.png 
$ 

对我来说是没问题的,两个图片是一样的。

5
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import codecs
f=codecs.open(u'仿宋人笔意.txt','r','utf-8')
print f.read()
f.close()

在这里运行得很好。

0

我尝试修改我的代码,重新写成了:

    destination = open(filename.encode("utf-8"), 'wb+')
    try:
        for chunk in f.chunks():
                destination.write(chunk)
        destination.close()
    except os.error:
        yield( "Error in Writing the File ",f.name)

这样就解决了我的错误。

谢谢大家花时间来回答我的问题。我没有尝试上面提到的那些选项,因为我已经能自己修复了,但还是感谢大家。

撰写回答