python cookbook 学习笔记 第五章 文件与IO (6) 使用操作类文件对象的程序来操作文本或者二进制字符串

  • 字符串的 I/O 操作
  • 问题:
    • 使用操作类文件对象的程序来操作文本或二进制字符串
  • 解决方案:
    `- 使用 io.StringIO()和io.BytesIO()类来创建文件对象操作字符串数据:
import io

s = io.StringIO()
s.write("Hello World\n")  # 12
print(s)  # <_io.StringIO object at 0x0000000001D9B318>

print("This is a test", file= s)
s.getvalue()
# 'Hello World\nThis is a test\n'

s = io.StringIO("hello\nworld\n")
s.read(4)  # hell
s.read()   # "o\nworld\n"
  • io.StringIO 只能用于文本。如果要操作二进制数据,要使用 io.BytesIO 类来代替:
s = io.BytesIO
s.write(b"binary data")
s.getvalue()
# (这种方法没有测试通过。。暂时不知道哪里出错。。。)
  • 讨论: 当你想模拟一个普通文件的时候, StringIO 和 BytesIO 类是很有用的。比如,在单元测试中,可以使用 StringIO 来创建一个包含测试数据的类文件对象,这个对象可以被传给某个参数为普通文件对象的函数。
  • StringIO 和 BytesIO 实例并没有正确的整数类型的文件描述符。因此,他们不能在需要使用真实的系统级文件、管 道或者是套接字的程序中使用。

猜你喜欢

转载自blog.csdn.net/qq_43539055/article/details/84889120
今日推荐