标签:读写文件 取数 bytesio 创建 实例 code get 就是 取数据
from io import StringIO
f= StringIO()
f.write('') # 写入
---》f.getvalue() #获取写入的数据(str)
--StringIO操作的只能是str!!
--读取StringIO,用一个str初始化StringIO,像读文件一样读取
BytesIO实现了在内存中读写bytes
>>> from io import BytesIO
>>> f = BytesIO()
>>> f.write('中文'.encode('utf-8'))
6
>>> print(f.getvalue())
b'\xe4\xb8\xad\xe6\x96\x87'
#读取数据
>>> from io import BytesIO
>>> f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
>>> f.read() # 只能读一次,再读为空。 可以把f.read()赋给某个变量,然后解码变量,显示值
#样式一:
>>> from io import StringIO # 导入StringIO类
>>> f = StringIO() # 创建一个实例,赋给f对象
>>> f.write('hello') # 往 f 中写入
5
>>> f.write(' ')
1
>>> f.write('world!')
6
>>> print(f.getvalue()) #getvalue()方法用于获得写入后的str
hello world!
#样式二:
>>> from io import StringIO
>>> f = StringIO('Hello!\nHi!\nGoodbye!') #创建一个带内容的实例
>>> while True: # while循环
... s = f.readline() # 按行读取内容
... if s == '':
... break
... print(s.strip()) # strip(),删除行首行尾的空格
标签:读写文件 取数 bytesio 创建 实例 code get 就是 取数据
原文地址:https://www.cnblogs.com/shaozheng/p/12011225.html