Python2向文件写入Unicode字符
来源:互联网 发布:卖家怎么弄淘宝客 编辑:程序博客网 时间:2024/05/16 03:58
总的思路:就是把所有unicode字符转化为utf-8编码格式然后写出文件。(为了节省内存,文件中数据并不直接以unicode格式存储,而是以utf-8存储)
1.向普通文本文件写入Unicode字符
python内置库中的open方法只能读写ascii码,如果想写入Unicode字符,需要使用codecs包
代码示例:
# -*- coding: utf-8 -*-import codecscontent = u'你好'f = codecs.open(r'c:/test.txt', 'w', 'utf-8')f.write(content)
我们可以看到codecs包中的open函数可以传入编码参数。
2.向csv文件中写入Unicode字符
csv模块也是默认不支持unicode字符,但是模块文档给出了处理unicode字符串的方法示例
代码示例:
# -*- coding: utf-8 -*-import csvimport codecsimport cStringIO# 这个类来自官方文档class UnicodeWriter: def __init__(self, f, dialect=csv.excel, encoding="utf-8-sig", **kwds): self.queue = cStringIO.StringIO() self.writer = csv.writer(self.queue, dialect=dialect, **kwds) self.stream = f self.encoder = codecs.getincrementalencoder(encoding)() def writerow(self, row): '''writerow(unicode) -> None This function takes a Unicode string and encodes it to the output. ''' self.writer.writerow([s.encode("utf-8") for s in row]) data = self.queue.getvalue() data = data.decode("utf-8") data = self.encoder.encode(data) self.stream.write(data) self.queue.truncate(0) def writerows(self, rows): for row in rows: self.writerow(row)name = u'BrownWong你好哈哈'with open(r'C:\Users\DELL\Desktop\test.csv', 'ab') as infile: writer = UnicodeWriter(infile, delimiter=',') writer.writerow([name])
注意:
1. 这里的open函数不能使用codecs模块里面的,而要使用内置库中的open函数。
2. 如果是以追加方式写入文件,假设文件存在,请确保此文件格式为utf-8.
Ref:
http://stackoverflow.com/questions/17245415/read-and-write-csv-files-including-unicode-with-python-2-7
https://docs.python.org/2/library/csv.html
1 0
- Python2向文件写入Unicode字符
- 向文件写入宽字符
- mysq,php写入unicode字符
- 向文件写入文本
- VBA 向文件写入简单数据(默认编码为ANSI或者Unicode)
- 基本文件的I/O --从字符串中读取字符&向字符串中写入字符
- Python2 Unicode
- 如何:向文件写入文本
- 向文件写入整数失败
- java向文件写入数据
- ios 向文件写入东西
- java向FTP写入文件
- 向数据库中写入文件
- java向文件中写入内容,字节流,字符流,缓冲,复制文件,设置字符编码 实例
- Tomcat应用向所在的linux环境中的文件写入中文字符乱码
- 关于Android开发向文件中写入中文字符出现乱码的问题解决
- c# 向字符串中写入字符
- 向控制台输出unicode中文字符
- C/C++ 局部变量与全局变量
- Linux进程间通信--命名管道
- 关于listview的item的焦点被强占的解决方法
- 【腾讯Bugly干货分享】Android Patch 方案与持续交付
- Xcode 自定义代码段
- Python2向文件写入Unicode字符
- 在body上添加的属性值是什么意思?
- 剑指offer面试题——从尾到头打印链表
- bootstrap摸态框链接到新页面问题
- xml文件,数据的存与取,PlayerPrefs
- 基于matlab的形态学处理
- 宏定义
- 沉浸式状态栏时和CoordinatorLayout一起时的坑
- Atom编辑器怎么去掉中间的虚线