桌面文件太多,如何一键整理
思路:
1.按文件类型分类整理整理成文件夹
2.按时间筛选需要整理的文件
3.万一出错,还原
import os
import time
import datetime
import sys
import shutil
desk='/Users/admin/Desktop'
three_days=time.time()-3600*24*0
def main(desk,three_days):
os.chdir(desk)
dirlist=os.listdir()
num=0
filepath=[os.path.join(desk,i) for i in dirlist if os.path.isfile(i) and os.path.getctime(i)<three_days]
print(filepath)
print('按文件类型整理{}前创建的文件'.format(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(three_days))))
cleanuppath=os.path.join(desk,'cleanup')
if not os.path.exists(cleanuppath):
os.mkdir(cleanuppath)
for j in filepath:
num+=1
suffix=os.path.splitext(j)[1][1:]
suffix_path=os.path.join(cleanuppath,suffix)
if not os.path.exists(suffix_path):
os.mkdir(suffix_path)
name = os.path.split(j)[1]
target_name = os.path.join(suffix_path,name)
try:
shutil.move(j,target_name)
except Exception as e:
print(e)
pass
print('整理{}份桌面文件至{}'.format(num,cleanuppath))
def get_all_file_path(desk):
desk=desk+'/cleanup'
for root, dirs, files in os.walk(desk):
if files:
for name in files:
yield os.path.join(root,name)
if __name__=='__main__':
com=sys.argv[1]
if com=='clean':
main(desk,three_days)
elif com=='back':
for paths in get_all_file_path(desk):
try :
shutil.move(paths,desk)
except Exception as e:
print(e)
else:
print('请输入正确的命令:clean,back')
break
代码主要用到os模块处理文件目录
网友评论