[Python] Using temporary files

José Castro
Devsys
Published in
1 min readAug 23, 2017

Working with lambda — jupyter, I saw the need to use cumbersome files through s3, which I had no intention of keeping in the file system, they were only temporary.

For that they are tempfile, which allows to create temporary files, with or without name, even the same module allows to create temporary directories to be able to work on them.

Creating and working a temporary file is as simple as using regular files:

import tempfilemy_file = tempfile.TemporaryFile()

As we do not specify the type of file opening, by default it is ‘w + b’, writing, reading and in bytes

data = "Bye World"# Python 3.x
my_file.write(bytes(data, 'UTF-8'))
# Python 2.x
my_file.write(data)
my_file.seek(0)# Python 3.x
print(my_file.read().decode())
# Python 2.x
print(my_file.read())

> Bye World

For close the file ( with the With statement works like a normal file) you can do the same for a normal file:

my_file.close()# Will return True if is really closed
my_file.closed

And that is the basic usage for tempfile, you can find more methods here, even you can use the NamedTemporaryFile, which you can give a name that persist in the FileSystem until you close it. You can access to the name using `my_file.name` and also you can save it into the FileSystem if you want.

As I told you at the beginning, I use this for works with s3 files so I wrote a little snippet if you want to use it.

--

--