DEV Community

Cover image for File-Like Objects in Python
bluepaperbirds
bluepaperbirds

Posted on

File-Like Objects in Python

Python supports file like objects, that don't write to the disk but stay in the memory.

You can create file like objects with StringIO. From Python version > 3 this is part of the io module.

These files live only inside the computer memory, not on the disk. Python can read files from the disk, but this article focuses on files in memory.

StringIO

To start using file-like objects, first import the io module. Then create a new file with io.StringIO() where the parameter is the file contents.

>>> import io
>>> 
>>> myFile = io.StringIO()

Now put some data into the file and read it with .read()

>>> myFile = io.StringIO("Data into the file")
>>> myFile.read()
'Data into the file'

Try to read it again, the file is empty?

>>> myFile.read()
''

No, the cursor is at the end. Set the cursor at position zero and you can read again.

>>> myFile.seek(0)
0
>>> myFile.read()
'Data into the file'
>>> 

You can mimick file like behavior with it:

>>> import io
>>> myFile = io.StringIO("Feeling good")
>>> data = myFile.read()
>>> print(data)
Feeling good
>>> 

Write file

You can write data into the memory file too, by using the .write() method. This method is part of the object and as parameter takes a string (there's also regular write file)

The .write() method lets you write any data into the file. The usual escape character work \n for a new line.

>>> myFile = io.StringIO("")
>>> myFile.write("Write a line into the file\n")
>>> myFile.write("Second line.\n")

Then read the file with .getvalue().

>>> data = myFile.getvalue()
>>> data
'Write a line into the file\nSecond line.\n'

Close the memory file:

>>> myFile.close()
>>> 

Related links:

Top comments (0)