Python deletes specified files using OS and GETOPT implementations

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.