Computer >> Computer tutorials >  >> Programming >> Python

How to delete all files in a directory with Python?


You can delete a single file or a single empty folder with functions in the os module.

Example

For example, if you want to delete a file my_file.txt,

>>> import os
>>> os.remove('my_file.txt')

The argument to os.remove must be absolute or relative path.

To delete multiple files, just loop over your list of files and use the above function. If you want to delete a folder containing all files you want to remove, you can remove the folder and recreate it as follows:

>>> import shutil
>>> shutil.rmtree('my_folder')
>>> import os
>>> os.makedirs('my_folder')

You can also recursively delete the files using os.walk().

Example

import os, re, os.path
mypath = "my_folder"
for root, dirs, files in os.walk(mypath):
    for file in files:
        os.remove(os.path.join(root, file))

The directory tree will be intact if above method is used.

hgjg