我能找到的就是这个 statement :
The easiest way to create a text stream is with open(), optionally specifying an encoding:
f = open("myfile.txt", "r", encoding="utf-8")In-memory text streams are also available as StringIO objects:
f = io.StringIO("some initial text data")
但是这完全没有告诉我什么时候应该使用 open() 而不是 io.StringIO ,反之亦然。我知道他们在幕后的工作方式并不完全相同。但为什么有人会选择 Python 3 中的 open() 呢?
请您参考如下方法:
不同之处在于:open 接受一个文件名(以及一些其他参数,如模式或编码),io.StringIO 接受一个纯字符串并且都返回类似文件对象。
因此:
- 使用
open读取文件; - 当您需要类似文件的对象并且想要传递字符串的内容时,请使用
StringIO。
StringIO 示例:
import csv
import io
reader = csv.reader(io.StringIO("a,b,c\n1,2,3"))
print ([r for r in reader])
# output [['a', 'b', 'c'], ['1', '2', '3']]
它非常有用,因为您可以在需要文件的地方使用字符串。
在通常情况下,如果您的磁盘上有一个 csv 文件,您会这样写:
with open(<path/to/file.csv>, ...) as f:
reader = csv.reader(f, ...)
