简体   繁体   中英

How to create a file with a hebrew name using python 2.7?

Here is my code (t.name holds a Hebrew name):

# -*- coding: utf8 -*-  
                title = '%s.html' % t.name
                with file(title, 'wb') as fpo:
                    fpo.write('<meta charset="utf-8">\n')                    
                    message = 'שלום לך %s' % t.name
                    fpo.write('%s\n' % message)

Here is how the file looks in the file system (windows 7): 希伯来语文件名

The content is presented fine by the browser.

What am I missing here?

Thanks, Omer.

The Windows filesystem uses UTF16 encoding. Your best bet is to use unicode values instead though, as Python will automatically use the correct codecs and APIs for your platform to encode filenames:

title = u'%s.html' % t.name.decode('utf8')  # decode from UTF8, use a unicode literal
with file(title, 'wb') as fpo:
    fpo.write('<meta charset="utf-8">\n')                    
    message = 'שלום לך %s' % t.name
    fpo.write('%s\n' % message)

尝试使用title=u'%s.html' % t.name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM