python利用os和getopt实现删除指定文件
2017-11-08 11:35
621 查看
工作中经常遇到要删除某些目录下的特定文件
例如删除xxx目录下的所有test开头文件或者.pyc结尾的文件
如果手动删除的话,很麻烦,写个程序自动删除
只需要运行的时候输入路径和文件名即可,不输入文件名则删除目录下所有文件
下面贴代码
例如删除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()
相关文章推荐
- Python3 利用函数 实现阶乘、列表中删除指定元素、等差数列求和
- python有关文件夹与文件的查找,删除等功能 在 os 模块中实现
- 利用脚步(bat文件)实现 删除指定目录下N天前的文件
- Python实现删除文件中含“指定内容”的行示例
- 利用python删除指定目录下,指定后缀名文件
- 【Python/PE】python中实现文件操作的几种功能(删除指定目录下的所有内容,文件复制等)
- Python实现删除文件但保留指定文件
- Python os.path和shutil模块实现文件复制、删除
- Python 实现指定目录下 删除指定大小的文件
- python脚本实现文件的批量移动、复制,以及删除指定后缀
- Python实现删除文件但保留指定文件
- 实现JFileChooser选择多文件放入JTable中,然后删除鼠标指定的行
- Python 实现文件复制、删除
- 利用Apache的commons-net实现FTP的文件读取、上传、下载、删除和移动功能
- Python实现删除目录下相同文件
- Python 实现在对一个目录下所有文件,指定某一行之后添加内容(批处理脚本)
- 删除当前文件夹下指定类型的文件 使用批处理实现
- Python_删除/创建指定目录及其下所有子目录的文件,该文件记录当前文件夹的内容
- 删除目录下相同文件 -> 逐级优化(python实现)
- Python 实现文件复制、删除