1. StringIOBytesIO
    2. StringIO
    3. 很多时候,数据读写不一定是文件,也可以在内存中读写。
    4. StringIO顾名思义就是在内存中读写str
    5. 要把str写入StringIO,我们需要先创建一个StringIO,然后,像文件一样写入即可:
    6. >>> from io import StringIO
    7. >>> f = StringIO()
    8. >>> f.write('hello')
    9. 5
    10. >>> f.write(' ')
    11. 1
    12. >>> f.write('world!')
    13. 6
    14. >>> print(f.getvalue())
    15. hello world!
    16. getvalue()方法用于获得写入后的str
    17. 要读取StringIO,可以用一个str初始化StringIO,然后,像读文件一样读取:
    18. >>> from io import StringIO
    19. >>> f = StringIO('Hello!\nHi!\nGoodbye!')
    20. >>> while True:
    21. ... s = f.readline()
    22. ... if s == '':
    23. ... break
    24. ... print(s.strip())
    25. ...
    26. Hello!
    27. Hi!
    28. Goodbye!
    29. BytesIO
    30. StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO
    31. BytesIO实现了在内存中读写bytes,我们创建一个BytesIO,然后写入一些bytes
    32. >>> from io import BytesIO
    33. >>> f = BytesIO()
    34. >>> f.write('中文'.encode('utf-8'))
    35. 6
    36. >>> print(f.getvalue())
    37. b'\xe4\xb8\xad\xe6\x96\x87'
    38. 请注意,写入的不是str,而是经过UTF-8编码的bytes
    39. StringIO类似,可以用一个bytes初始化BytesIO,然后,像读文件一样读取:
    40. >>> from io import BytesIO
    41. >>> f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
    42. >>> f.read()
    43. b'\xe4\xb8\xad\xe6\x96\x87'
    44. 小结
    45. StringIOBytesIO是在内存中操作strbytes的方法,使得和读写文件具有一致的接口。
    46. 参考源码
    47. do_stringio.py
    48. do_bytesio.py