Reputation: 13218
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
Reputation: 493
This:
filename.encode('utf-8')
tries to convert filename from ascii
encoding to utf-8
and causes the error.
Upvotes: 0
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
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
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
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