Work frequently encountered to delete specific files under certain directories
For example, delete all the test start files in the xxx directory or the files ending with the. PYc
If manually deleted, it is troublesome to write a program to automatically delete
Just enter the path and file name when you need to run, delete all the files in the directory without entering the file name
Paste the following code
#-*-coding:utf-8-*-"""This was a program to delete specified files"""ImportOSImportSYSImportgetoptdefusage ():Print 'This was a program to delete all specified files in the specified path\n' '- H--help Show this usage\n' '- f--filename Delete all files start with the This filename, such as test or pyc\n if not specified, delete all files' '- p--path Delete files from the specified path\n'defget_argument ():Try: Path="'filename="'opts, args= Getopt.getopt (sys.argv[1:],'hf:p:', ['--help','--filename','--path']) forO, ainchopts:ifOinch['- H','--help']: Usage () sys.exit ()ifOinch['- F','--filename']: filename=aifOinch['- P','--path']: Path=aiffilename:delete_files_with_filename (path, filename)Else: Delete_all_files (path)exceptgetopt. Getopterror:usage () sys.exit ( )defDelete_files_with_filename (Path, filename=None): Del_list=os.listdir (path) forFinchDel_list:filepath=Os.path.join (path, f)ifOs.path.isfile (filepath):ifFileNameinchf:os.remove (filepath)elifOs.path.isdir (filepath): Delete_files_with_filename (filepath, filename)defdelete_all_files (path): Del_list=os.listdir (path) forFinchDel_list:filepath=Os.path.join (path, f)ifOs.path.isfile (filepath): Os.remove (filepath)elifOs.path.isdir (filepath): Delete_all_files (filepath) os.rmdir (filepath)if __name__=='__main__': Get_argument ()
Python deletes specified files using OS and GETOPT implementations