文字列によるファイルオブジェクトfile objectの作成

559 ワード

Open()関数はfile objectを作成できますが、writeやreadなどのメソッドを持つfile objectを文字列で作成できますか?io.StringIO関数
import io
f = io.StringIO("some initial text data")

file objectはfile-like object、streamとも呼ばれるのでio.StringIOは具体的にIn-memory text streamsを作成し、io.BytesiOはIn-memory binary streamsを作成できます
使用状況:一部の関数でfile objectが使用され、file objectに含まれるデータがメモリに格納されている場合があります.
参考リンクstackoverflowでの回答https://stackoverflow.com/questions/44672524/how-to-create-in-memory-file-object/44672691#44672691ioライブラリhttps://docs.python.org/3/library/io.html#text-i-o