无法在Python中打开带有日文文件名的文件

时间:2015-12-03 15:54:29

标签: python-2.7 unicode

为什么这不适用于Python解释器?我在Windows 7上运行Python 2.7版本的python.exe。我的语言环境是en_GB。

open(u'黒色.txt')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 22] invalid mode ('r') or filename: u'??.txt'

该文件确实存在,并且可读。

如果我尝试

name = u'黒色.txt'
name

翻译显示

u'??.txt'

其他:

好的,我试图为了这个论坛的目的简化我的问题。最初文件名是从带有文件选择器的网页到达cgi脚本。我们的想法是让网页用户将文件上传到服务器:

import cgi
form = cgi.FieldStorage()
fileItems = form['attachment[]']

for fileItem in fileItems:
    if fileItem.file:
        fileName = os.path.split(fileItem.filename)[1]

        f = open(fileName, 'wb')
        while True:
            chunk = fileItem.file.read(100000)
            if not chunk: 
                break
            f.write(chunk)
        f.close()

但是在服务器端创建的文件名称已损坏。我开始在Python解释器中对此进行调查,重现了问题(我想到了),这就是我在原始问题中提出的问题。但是,我认为现在我设法创建了一个单独的问题。

感谢下面的答案,我修复了cgi脚本,确保文件名被视为unicode:

fileName = unicode(os.path.split(fileItem.filename)[1])

我从未在解释器中找到工作的例子。我怀疑那是因为我的电脑有错误的语言环境。

2 个答案:

答案 0 :(得分:0)

这是一个读写文件的示例脚本。您可以对支持您正在编写的字符的源文件使用任何编码,但请确保#coding行匹配。只要encoding参数匹配,就可以对数据文件使用任何编码。

#coding:utf8
import io
with io.open(u'黒色.txt','w',encoding='utf8') as f:
    f.write(u'黒色.txt content')

with io.open(u'黒色.txt',encoding='utf8') as f:
    print f.read()

输出:

黒色.txt content

注意print仅在运行脚本的终端支持日语时才有效;否则,你可能会获得UnicodeEncodeError。我在Windows上使用支持UTF-8输出的IDE,因为Windows控制台使用的是不支持日语的传统US-OEM编码。

答案 1 :(得分:0)

如果要在Python中以交互方式使用Unicode字符串,请运行IDLE。然后输入或打印任何字符都可以正常工作。

相关问题