CWYAlpha

Just another WordPress.com site

Thought this was cool: Python中向gz(gzip)文件中写入utf8(utf-8)字符串

leave a comment »


这是一个内牛满面的问题,我从半年前开始找这个问题的答案,今天才解决……

需求版本1:我需要将字符串直接写入成以gz格式,这个很简单。

import gzip
fp = gzip.open("file", "wb")
fp.write(data)
fp.close()

需求版本2:现在字符串data需要是utf-8的,上述方法就不行了,解决方法:

import codecs
gzfp = gzip.open("file", "wb")
writer = codecs.getwriter("utf-8")(self.gzfp)
writer.write(data)
gzfp.close()
writer.close()

读取也是累死得

fd0 = gzip.open(fname, 'rb')
fd = codecs.getreader("utf-8")(fd0)
data = fd.readline()

from 四号程序员四号程序员: http://www.coder4.com/archives/3647

Written by cwyalpha

十月 17, 2012 在 5:18 上午

发表在 Uncategorized

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s

%d 博主赞过: