1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
import os
import argparse
def get_all_files(path,ext,size):
all_files = []
for root, _dirs, files in os.walk(path):
for filename in files:
if ext is None or filename.endswith(ext):
file_path = os.path.join(root, filename)
if os.path.getsize(file_path) < size:
all_files.append(file_path)
return all_files
def remove(all_files):
for filename in all_files:
info_file = os.path.splitext(filename)[0] + '.txt'
os.remove(filename)
if os.path.exists(info_file):
os.remove(info_file)
def show_filesize(file_path):
size = os.path.getsize(file_path)
if size < 1024:
return str(size) + 'B'
elif size < 1024 * 1024:
return str(round(size / 1024, 2)) + 'KB'
elif size < 1024 * 1024 * 1024:
return str(round(size / 1024 / 1024, 2)) + 'MB'
else:
return str(round(size / 1024 / 1024 / 1024, 2)) + 'GB'
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='一个按大小删除文件的脚本')
parser.add_argument('-f','--folder',type=str,default=os.getcwd(), help='要操作的文件夹')
parser.add_argument('-s','--size', type=int, help='文件大小,单位为KB',default=0)
parser.add_argument('-e','--ext', type=str, help='文件类型')
parser.add_argument('-ch','--check', type=bool, help='是否检查文件大小',default=False)
args = parser.parse_args()
size = args.size * 1024
all_files = get_all_files(args.folder,args.ext,size)
if args.check:
for filename in all_files:
print(filename,show_filesize(filename))
else:
print('remove...')
remove(all_files)
print('done')
|