【问题标题】:How to create a file with a hebrew name using python 2.7?如何使用 python 2.7 创建具有希伯来语名称的文件?
【发布时间】:2013-08-05 12:59:41
【问题描述】:

这是我的代码(t.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)

这是文件在文件系统中的外观(Windows 7):

浏览器可以很好地呈现内容。

我在这里错过了什么?

谢谢, 奥马尔。

【问题讨论】:

    标签: python windows encoding io


    【解决方案1】:

    Windows 文件系统使用 UTF16 编码。不过,最好的办法是使用 unicode 值,因为 Python 会自动为您的平台使用正确的编解码器和 API 来编码文件名:

    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)
    

    【讨论】:

      【解决方案2】:

      试试title=u'%s.html' % t.name

      【讨论】:

      • 这并没有提供问题的答案。要批评或要求作者澄清,请在其帖子下方发表评论。
      • @Arpit 我不在 Windows 上。即使我认为它应该有效,我也无法尝试该解决方案。我提出了一个解决方案,不是批评,也不是要求澄清。 BTW Martijn 对此进行了详细回答。 :)
      猜你喜欢
      • 2013-11-08
      • 1970-01-01
      • 1970-01-01
      • 2020-11-30
      • 2011-09-01
      • 2015-06-17
      • 2014-12-14
      • 2013-08-07
      • 2010-10-04
      相关资源
      最近更新 更多