python利用os和getopt实现删除指定文件

工作中经常遇到要删除某些目录下的特定文件

例如删除xxx目录下的所有test开头文件或者.pyc结尾的文件

如果手动删除的话,很麻烦,写个程序自动删除

只需要运行的时候输入路径和文件名即可,不输入文件名则删除目录下所有文件

下面贴代码

# -*- coding:utf-8 -*-
"""
    this is a program to delete specified files
"""

import os
import sys
import getopt

def usage():
    print 'this is 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 this filename, such as test or pyc\n if not specified, delete all files' \
          '-p --path delete files from the specified path\n'

def get_argument():
    try:
        path = ''
        filename = ''
        opts, args = getopt.getopt(sys.argv[1:], 'hf:p:', ['--help', '--filename', '--path'])
        for o, a in opts:
            if o in ['-h', '--help']:
                usage()
                sys.exit()
            if o in ['-f', '--filename']:
                filename = a
            if o in ['-p', '--path']:
                path = a
        if filename:
            delete_files_with_filename(path, filename)
        else:
            delete_all_files(path)
    except getopt.GetoptError:
        usage()
        sys.exit()

def delete_files_with_filename(path, filename=None):
    del_list = os.listdir(path)
    for f in del_list:
        filepath = os.path.join(path, f)
        if os.path.isfile(filepath):
            if filename in f:
                os.remove(filepath)
        elif os.path.isdir(filepath):
            delete_files_with_filename(filepath, filename)

def delete_all_files(path):
    del_list = os.listdir(path)
    for f in del_list:
        filepath = os.path.join(path, f)
        if os.path.isfile(filepath):
            os.remove(filepath)
        elif os.path.isdir(filepath):
            delete_all_files(filepath)
            os.rmdir(filepath)

if __name__ == '__main__':
    get_argument()

转载于:https://www.cnblogs.com/lgh344902118/p/7803237.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值