[Python] regularly delete folders and files in the specified directory

Tip: After the article is written, the table of contents can be automatically generated. How to generate it can refer to the help document on the right


foreword

This article briefly introduces writing Python scripts to delete files and folders in the directory, which can achieve the purpose of regular deletion. In some scenarios, files will be written to the directory continuously at regular intervals. Keeping this state for a long time will generate a large number of files in the directory and take up a lot of hard disk space. In this case, we can regularly delete the files in the directory to release hardware space resources.


1. Steps to use

1. Import library.

Need to import os, shutil, time libraries, os and shil are mainly used to delete files and delete folders, time is mainly used to control the time of scheduled deletion.

import os,time,shutil

2. Set the directory to be deleted, the directory will not be deleted, and the files and folders under the directory will be deleted.

Set a variable to store the directory to be deleted. The code example is as follows:

targetdir = r"E:\test" 

3. Delete the file folder and print the deletion time

Create a list to save all file names in this directory. The file name is processed, and the content in all lists is judged in a loop. If it is a file, the file is deleted, and if it is a folder, the folder is deleted. Write it in the while loop and set the deletion interval. The code example is as follows:

files = []
while True:
    files = os.listdir(targetdir)               
    for fileitem in files:
        fileroute = os.path.join(targetdir, fileitem)   
        if os.path.isfile(fileroute):            
            os.remove(fileroute)                 
        elif os.path.isdir(fileroute):
            shutil.rmtree(fileroute,True)        
    print("%s 目录文件和文件夹删除成功" % (time.strftime("%Y/%m/%d %H:%M:%S")))
    time.sleep(5) 

The scheduled deletion time interval set in the script is 5 seconds, and the parameters in sleep can be modified according to the actual situation. The effect is as follows:
renderings


Summarize

This article mainly introduces the deletion of files and folders in the specified directory in python, and the deletion operation can be performed regularly.

Guess you like

Origin blog.csdn.net/liaotianyin/article/details/130509964