PythonIO模块的使用
发布时间:2025-08-31 21:51:41
作者:益华网络
来源:undefined
浏览量(0)
点赞(0)
摘要:今天学习IO模块的使用,主要分为StringIO的使用和BytesIO的使用~ 1.StringIO的使用# 类似文件的缓冲区from io importStringIOcache_file =StringIO()print(cache_file.write(hello world))# 11print(cache_file.seek(0))# 0print(cache_file.read())# hell
今天学习IO模块的使用,主要分为StringIO的使用和BytesIO的使用~
1.StringIO的使用# 类似文件的缓冲区from io importStringIOcache_file =StringIO()print(cache_file.write(hello world))# 11print(cache_file.seek(0))# 0print(cache_file.read())# hello worldprint(cache_file.close())# 释放缓冲区 StringIO经常被用来作字符串的缓存,因为StringIO的一些接口和文件操作是一致的,也就是说同样的代码,可以同时当成文件操作或者StringIO操作; 要读取StringIO,可以用一个str初始化StringIO,然后像读文件一样读取; 当使用read()方法读取写入的内容时,则需要先用seek()方法让指针移动到最开始的位置,否则读取不到内容(写入后指针在最末尾); getvalue()方法:直接获得写入后的str; close()方法:在关闭文件的缓冲区之后就不能再进行读写操作了; 2.BytesIO的使用# 类似文件的缓冲区from io importBytesIObytes_file =BytesIO()bytes_file.write(bhello world)bytes_file.seek(0)print(bytes_file.read())# bhello worldbytes_file.close() StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO; BytesIO实现了在内存中读写bytes,写入的不是str,而是经过UTF-8编码的bytes; 要读取BytesIO,可以用一个bytes初始化BytesIO,然后像读文件一样读取;扫一扫,关注我们
声明:本文由【益华网络】编辑上传发布,转载此文章须经作者同意,并请附上出处【益华网络】及本页链接。如内容、图片有任何版权问题,请联系我们进行处理。
0