Mahendra Liya
Mahendra Liya

Reputation: 13218

How to open a file with chinese name in python

I am trying to open a file in "w" mode with "open()" function in python.

The filename is : 仿宋人笔意.jpg.

The open function fails with this filename but succeeds with normal files.

How can I open a file with names which are not in English in python?

My code is as follows:

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")

I always get "Error while opening the file" for non-english filenames.

Thanks in advance.

Upvotes: 3

Views: 7801

Answers (5)

Gregory
Gregory

Reputation: 493

This:

filename.encode('utf-8') 

tries to convert filename from ascii encoding to utf-8 and causes the error.

Upvotes: 0

Mahendra Liya
Mahendra Liya

Reputation: 13218

I tried modifying my code and rewrote it as:

    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)

And it solved my error.

Thank you everyone for taking time to answer. I haven't tried the options mentioned above as I was able to fix it, but thanks everybody.

Upvotes: 0

user18015
user18015

Reputation:

If you're having a problem it seems more likely to do with your operating system or terminal configuration than Python itself; it worked ok for me even without using the codecs module.

Here's a shell log of a test that opened an image file and copied it into a new file with the Chinese name you provided:

$ 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 
$ 

Worked for me, the images are the same.

Upvotes: 4

Robus
Robus

Reputation: 8259

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

worked just fine here

Upvotes: 5

theheadofabroom
theheadofabroom

Reputation: 22019

If you yield your filename does it look right? I'm not sure if the filname has been mangled before reaching this code segment.

Upvotes: 0

Related Questions