kyoh
kyoh

Reputation: 11

Deleting all files in a folder in Python

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.

Upvotes: 0

Views: 2374

Answers (1)

jfs
jfs

Reputation: 414585

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

Upvotes: 2

Related Questions