python中IO库中StringIO方法和BytesIO方法用法详解
2023-09-11 14:15:15 时间
有时候数据读写不一定是文件,也可以在内存中读写。StringIO顾名思义就是在内存中读写str。
Python在内存中读写数据,用到的模块是StringIO和BytesIO。
getvalue()方法用于获得写入后的str。
StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO。
StringIO用法:
源码解释:
class StringIO(_TextIOBase):
"""
Text I/O implementation using an in-memory buffer.
The initial_value argument sets the value of object. The newline
argument is like the one of TextIOWrapper's constructor.
"""
示例代码1:
# StringIO:在内存中读写str
from io import StringIO
f = StringIO()
print(f.write('hello'))
print(f.write(' '))
print(f.write('world!'))
# getValue()方法用于获取写入的str
print(f.getvalue())
print('-----------------------1')
# 要读取StringIO,可以用一个str初始化StringIO,然后,像读文件一样读取:
f = StringIO('Hello!\nHi!\nGoodbye!')
while True:
s = f.readline()
if s == '':
break
print(s.strip())
print('-----------------------2')
运行结果:
BytesIO用法:
# 源码解释:
class BytesIO(_BufferedIOBase):
""" Buffered I/O implementation using an in-memory bytes buffer. """
示例代码2:
# StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO
from io import BytesIO
f = BytesIO()
print(f.write('中国\n我爱你'.encode('utf-8')))
print(f.getvalue())
print('-----------------------1')
# 和StringIO类似,可以用一个bytes初始化BytesIO,然后,像读文件一样读取
f = BytesIO(b'\xe4\xb8\xad\xe5\x9b\xbd\n\xe6\x88\x91\xe7\x88\xb1\xe4\xbd\xa0')
print(f.read())
while True:
s = f.readline()
if s == b'':
break
print(s.strip())
print('-----------------------2')
运行结果:
相关文章
- Python之——python-nmap的安装与常用方法说明
- python使用datetime模块计算各种时间间隔的方法
- Python生成随机数组的方法小结
- 朴素贝叶斯算法的python实现方法
- Python 保存数据的方法:
- Python基于正则表达式实现文件内容替换的方法
- 用Python实现一个大数据搜索引擎
- python正常时间和unix时间戳相互转换的方法
- Atitit 文件上传 架构设计 实现机制 解决方案 实践java php c#.net js javascript c++ python
- Python编程语言学习:基于python各种库(matplotlib、Image)利用多种方法展示图片或进行图片可视化之详细攻略
- Python编程语言学习:python语言中快速查询python自带模块&函数的用法及其属性方法、如何查询某个函数&关键词的用法、输出一个类或者实例化对象的所有属性和方法名之详细攻略
- IDE之Eric:Python的IDE之eric的简介、安装、使用方法之详细攻略
- Python之matplotlib:基于matplotlib库利用python语言实现一张画布显示多张图的多种方法
- Python之ffmpeg:利用python编程基于ffmpeg将m4a格式音频文件转为mp3格式文件
- Python语言学习之双下划线那些事:python和双下划线使用方法之详细攻略
- Python小游戏(打乒乓)
- 哆啦A梦和小猪佩奇(Python实现)
- 停止使用 Python 循环,这三种方法效果更棒
- Python LOGGING使用方法
- 多版本Python共存时pip给指定版本的python安装package的方法
- 【异常】前端ERR! stack Error: Can‘t find Python executable “python“, you can set the PYTHON env variable.