Day24:IO模块的使用

今天学习IO模块的使用,主要分为StringIO的使用和BytesIO的使用~

1.StringIO的使用

# 类似文件的缓冲区
from io import StringIO
cache_file = StringIO()
print(cache_file.write('hello world')) # 11
print(cache_file.seek(0)) # 0
print(cache_file.read()) # hello world
print(cache_file.close())  # 释放缓冲区
  • StringIO经常被用来作字符串的缓存,因为StringIO的一些接口和文件操作是一致的,也就是说同样的代码,可以同时当成文件操作或者StringIO操作;

  • 要读取StringIO,可以用一个str初始化StringIO,然后像读文件一样读取;

  • 当使用read()方法读取写入的内容时,则需要先用seek()方法让指针移动到最开始的位置,否则读取不到内容(写入后指针在最末尾);

  • getvalue()方法:直接获得写入后的str;

  • close()方法:在关闭文件的缓冲区之后就不能再进行读写操作了;

2.BytesIO的使用

# 类似文件的缓冲区
from io import BytesIO
bytes_file = BytesIO()
bytes_file.write(b'hello world')
bytes_file.seek(0)
print(bytes_file.read()) # b'hello world'
bytes_file.close()
  • StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO;

  • BytesIO实现了在内存中读写bytes,写入的不是str,而是经过UTF-8编码的bytes;

  • 要读取BytesIO,可以用一个bytes初始化BytesIO,然后像读文件一样读取;

猜你喜欢

转载自blog.csdn.net/ivenqin/article/details/87934164
今日推荐