您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python写unicode容易文件?

5b51 2022/1/14 8:22:02 python 字数 3761 阅读 534 来源 www.jb51.cc/python

我想确保我的代码中的所有字符串都是unicode,所以我使用unicode_literals,然后我需要将字符串写入文件:from __future__ import unicode_literals with open('/tmp/test', 'wb') as f: f.write('中文') # UnicodeEncodeError 所以我需要

概述

我想确保我的代码中的所有字符串都是unicode,所以我使用unicode_literals,然后我需要将字符串写入文件

from __future__ import unicode_literals
with open('/tmp/test','wb') as f:
    f.write("中文") # UnicodeEncodeError

所以我需要这样做:

from __future__ import unicode_literals
with open('/tmp/test','wb') as f:
    f.write("中文".encode("utf-8"))
    f.write("中文".encode("utf-8"))
    f.write("中文".encode("utf-8"))
    f.write("中文".encode("utf-8"))

但每次我需要在代码中编码时,我都很懒,所以我改为编解码器:

from __future__ import unicode_literals
from codecs import open
import locale,codecs
lang,encoding = locale.getdefaultlocale()

with open('/tmp/test','wb',encoding) as f:
    f.write("中文")

如果我只想写文件,任何更简单的方法,我还是认为这太过分了?

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import io

with io.open('/tmp/test','w') as file:
    file.write(u"中文" * 4)

它使用locale.getpreferredencoding(False)字符编码将Unicode文本保存到文件中.

在Python 3上:

>您不需要使用显式编码声明(# – * – coding:utf-8 – * – ),在Python源代码中使用文字非ascii字符. utf-8是认值.
>你不需要使用import io:builtin open()就是io.open()
>您不需要使用u”(u前缀). ”认情况下,文字是Unicode.如果你想省略你”然后从__future__中恢复导入unicode_literals,就像问题中的代码一样.

即,完整的Python 3代码是:

#!/usr/bin/env python3

with open('/tmp/test','w') as file:
    file.write("中文" * 4)

总结

以上是编程之家为你收集整理的python写unicode容易文件?全部内容,希望文章能够帮你解决python写unicode容易文件?所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶