0

I am trying to make a program in Python that will delete all files in the %temp% path, also known as C:\Users\User\AppData\Local\Temp.

How can I do this? I am using Python 3.4.

Michael Currie
  • 13,721
  • 9
  • 42
  • 58
kyoh
  • 11
  • 1
  • note: On POSIX, a temporary directory may have a sticky bit set: [*"When a directory's sticky bit is set, the filesystem treats the files in such directories in a special way so only the file's owner, the directory's owner, or root user can rename or delete the file."*](https://en.wikipedia.org/wiki/Sticky_bit) i.e., you might not have permission to delete all files in the temporary directory. – jfs Jul 02 '15 at 13:34
  • I don't believe this particular question is a duplicate as the OP is asking about temporary folder deletion. The linked answer doesn't reference the temp folder. For temp files, you can use the tempfile module. – drohm Jul 02 '15 at 16:17
  • possible duplicate of [How to remove tempfile in python](http://stackoverflow.com/questions/30793080/how-to-remove-tempfile-in-python) – jezrael Jul 03 '15 at 12:34

1 Answers1

2

In general, you could use shutil.rmtree() to delete all files/directories in a folder:

#!/usr/bin/env python
import shutil
import tempfile

dirpath = tempfile.mkdtemp()
try:
    # use the temporary directory here
    ...
finally:
    shutil.rmtree(dirpath) # clean up

The above can be written simpler if it is all you need (create a temporary directory from scratch):

#!/usr/bin/env python3
import tempfile

with tempfile.TemporaryDirectory() as dir:
    print(dir.name) # use the temporary directory here
jfs
  • 399,953
  • 195
  • 994
  • 1,670