Removing a temporary file in Python

python temporary file example
python remove file
making a temp file in python
python create temporary csv file
python named temporary file suffix
python create temp excel file
flask tmp file
python remove directory

This is my existing code to zip a folder which I have put together mostly from help on here:

#!/usr/bin/env python

import os
import sys
import datetime

now = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M")
target_dir = '/var/lib/data'
temp_dir='/tmp'

zip = zipfile.ZipFile(os.path.join(temp_dir, now+".zip"), 'w', zipfile.ZIP_DEFLATED)
rootlen = len(target_dir) + 1
for base, dirs, files in os.walk(target_dir):
   for file in files:
      fn = os.path.join(base, file)
      zip.write(fn, fn[rootlen:])

If I wanted to remove the zip file I just created at the end of the opperation, would the best command be this?

os.remove.join(temp_dir, now+".zip")

The os.remove(os.path.join(temp_dir, now + ".zip")) will be fine.

However, you should ensure that it is executed properly in every case you want it to.

If it is to be removed in any case, you could do

create it
try:
    work with it
finally:
    remove it

But in this case, you could as well use the tempfile module:

import tempfile
with tempfile.NamedTemporaryFile(suffix='.zip') as t:
    z = zipfile.ZipFile(t.name, 'w') # re-create it
    do stuff with z
# after the with clause, the file is gone.

If, however, you want it to be gone only under special circumstances (on success, on error, ...) you are stuck with os.remove(os.path.join(temp_dir, now+".zip")) and you should use it whenever the file is to be deleted.

try:
    do_stuff
except VerySpecialException:
    os.remove(os.path.join(temp_dir, now+".zip")) # do that here for a special exception?
    raise # re-raise
except: # only use a bare except if you intend to re-raise
    os.remove(os.path.join(temp_dir, now+".zip")) # or here for all exceptions?
    raise # re-raise
else:
    os.remove(os.path.join(temp_dir, now+".zip")) # or here for success?

tempfile — Generate temporary files and directories, On completion of the context or destruction of the file object the temporary file will be removed from the filesystem. The mode parameter defaults to 'w+b' so that  We can use os.remove() function in order to remove a file. We should import the os module in order to use remove function. In this example, we will remove the file named trash .


This would be the way to do it:

os.remove(os.path.join(temp_dir, now+".zip"))

have fun, Mike

10.6. tempfile — Generate temporary files and directories, It will be destroyed as soon as it is closed (including an implicit close when the object is garbage collected). Under Unix, the directory entry for the file is removed​  Return a file-like object that can be used as a temporary storage area. The file is created securely, using the same rules as mkstemp (). It will be destroyed as soon as it is closed (including an implicit close when the object is garbage collected).


Consider using Python's built in temporary file library. It handles the cleanup of the tempfile when it is closed.

Create, use, and remove temporary files securely, The best part is that the temporary file created by TemporaryFile() will be removed automatically whenever it the file is closed. Also, it does not create any reference  All you need to do to remove a file is call os.remove () with the appropriate filename and path (Python defaults to the current directory, so you don’t need to specify a path if the file you want to remove is in the default directory). The ease with which you can perform this task is almost scary because it’s too easy.


The Python tempfile Module, The file created by TemporaryFile() is removed automatically when it is closed. import os import tempfile print 'Building a file name yourself:' filename  Introduction Temporary files, or "tempfiles", are mainly used to store intermediate information on disk for an application. These files are normally created for different purposes such as temporary backup or if the application is dealing with a large dataset bigger than the system's memory, etc. Ideally, these files are located in a separate directory, which varies on different operating


tempfile – Create temporary filesystem resources., What is important, the file's entry in temp folder is removed as soon as the file object is closed. Following code shows usage of TemporaryFile()  This module generates temporary files and directories. It works on all supported platforms. In version 2.3 of Python, this module was overhauled for enhanced security. It now provides three new functions, NamedTemporaryFile(), mkstemp(), and mkdtemp(), which should eliminate all remaining need to use the insecure mktemp() function. Temporary file names created by this module no longer contain the process ID; instead a string of six random characters is used.


Generate temporary files and directories using Python, In other words, you just want to control when the file gets removed from disk. from tempfile import NamedTemporaryFile # When delete=False is  Python Overview Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods Python File Methods Python Keywords Python Exceptions Python Glossary Module Reference Random Module Requests Module Math Module cMath Module Python How To Remove List Duplicates Reverse a String