Using io.StringIO to Simulate a File
00:00
So a way that you can simulate such a file object is by importing StringIO
from the io
module. So we’ll say from io import StringIO
.
00:13
And StringIO
is a file-like object that lives inside your memory. So I can create this, let’s call it fake_file
00:25
and it’ll be a StringIO
object and I’ll pass it some text.
00:37
Now if I look at fake_file
, you can see that it’s a StringIO
object, a certain memory location. And the fun thing with this is that it basically supports everything that file-like object, like the one you get from using open()
also supports.
00:52
So I can read this fake_file
in the same way and you can see that I get as an output the text that I passed it. Note that if you try to read it again it’s empty because just like another file, like object, Python reads to the end and then there’s nothing more to read.
01:10
So therefore you get the empty string as an output. But just like with another file-like object, you can also go back to the beginning by using .seek()
and passing in zero.
01:21
That goes back to the beginning and now I can read again and I get the output another time. Now let’s go back to the beginning again and I want to show you that you can also use a function that takes usually a file-like object and does something with it, right in the same way with the StringIO
object.
01:40
So I can call upcase_file_content()
and pass it my fake_file
01:45
and you can see that it processes it just like it did before with the object that you got returned when using open()
.
01:54
So using StringIO
is a way that you can simulate working with a file object on disk, but instead this fake file object only lives in your memory.
02:07
And I mentioned that StringIO
shares a lot with the object that you get when using open()
. So in the next lesson, let’s take a look at what these two objects are, how they’re similar, and how they’re different from each other.
Become a Member to join the conversation.