Python中文
首页
教程
问答
标签
搜索
登录
注册
python很容易将unicode写入文件?
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>我想确保代码中的所有字符串都是unicode,所以我使用<code>unicode_literals</code>,然后需要将字符串写入文件:</p> <pre><code>from __future__ import unicode_literals with open('/tmp/test', 'wb') as f: f.write("中文") # UnicodeEncodeError </code></pre> <p>所以我需要这样做:</p> <pre><code>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")) </code></pre> <p>但每次我需要编码时,我都很懒,所以我改为编解码器:</p> <pre><code>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("中文") </code></pre> <p><strong>如果我只想写入文件,我仍然认为这太多了,还有更简单的方法吗?</strong></p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>这个解决方案怎么样?</p> <p><a href="https://stackoverflow.com/questions/934160/write-to-utf-8-file-in-python">Write to UTF-8 file in Python</a></p> <p>只有三行代码。</p>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
如何合并多个PDF文件?
3 回答
如何合并多个xarray数据变量及其坐标?
1 回答
如何合并多个列中具有重复值的行
5 回答
如何合并多个唯一id
7 回答
如何合并多个图纸并使用图纸名称的名称重命名列名?
9 回答
如何合并多个字典并添加同一个键的值?(Python)
1 回答
如何合并多个搜索结果文件(pkl)以将它们全部打印在一起?
2 回答
如何合并多个数据帧
6 回答
如何合并多个数据帧并使用Pandas为假人添加列?
9 回答
如何合并多个数据帧并按时间戳排序
9 回答
如何合并多个数据帧的列表并用另一个lis标记每列
4 回答
如何合并多个数据框中的列
8 回答
如何合并多个文件?
3 回答
如何合并多个查询集?
6 回答
如何合并多个绘图?
10 回答
如何合并多个词典
1 回答
如何合并多个输入数据集(数据帧)?
4 回答
如何合并多条记录中拆分的文本行
1 回答
如何合并多索引列datafram
9 回答
如何合并多级(即多索引)数据帧?
2 回答