@Scrazy
2016-02-15T08:41:06.000000Z
字数 1038
阅读 1099
python学习笔记
读写数据时并不一定是文件
,也可以在内存
中读写。StringIO
就是在内存中读写str
。
>>> from io import StringIO
>>> f = StringIO()
>>> f.write('Hello World')
11
>>> f.write('\nI Like Python')
14
>>> print(f.getvalue())
Hello World
I Like Python
getvalue()
方法用于获得写入后的str
我们也可以使用循环
的方法来读取文件:
>>> from io import StringIO
>>> f = StringIO('Hello!\nWorld!\nI Like Python')
>>> while True:
... s = f.readline()
... if s == '': # 读取完成则break
... break
... print(s.strip())#strip()是为了去掉转行的空行
...
Hello!
World!
I Like Python
下面是print(s)
的输出结果(区别于print(s.strip()
)
>>> from io import StringIO
>>> f = StringIO('Hello\nI\nLike\nPython')
>>> while True:
... s = f.readline()
... if s == '':
... break
... print(s)
...
Hello
I
Like
Python
StringIO
操作只能是str
,对于二进制数据的操作就需要使用BytesIO
>>> from io import BytesIO
>>> f = BytesIO()
>>> f.write('中文'.encode('utf-8'))
6
>>> print(f.getvalue())
b'\xe4\xb8\xad\xe6\x96\x87'
写入的数据是经过UTF-8
编码过的bytes
不是str
。
和StringIO
类似,也可以用一个bytes初始化一个BytesIO
然后像读取文件一样读取:
>>> from io import StringIO
>>> f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87\xff\xfe-N\x87e')#这是`utf-16`的‘中文’('中文'.encode('utf-16'))
>>> f.read()
b'\xe4\xb8\xad\xe6\x96\x87\xff\xfe-N\x87e'