递归删除超过2年的文件(具有.zip,.log等特定扩展名)

问题描述 投票:0回答:1

我是Python的新手,想要编写一个脚本,以递归方式删除超过2年的目录(及其子目录)中的文件,并具有.zip,.txt等特定扩展名。

python-3.7
1个回答
0
投票

我知道这不是GitHub但是:我花了很多时间试图解决它,我不得不承认答案不是那么明显,但我最终找到了它。我不知道为什么我花了半个小时在这个随机程序上,但我做到了。幸运的是我也使用python 3.7,因为我没有在帖子的底部看到你的标签。 This Image是我运行名为The Program的演示

Features

- 删除目录和子目录中的所有文件 - 能够将扩展名更改为您想要的任何内容,例如:txt,bat,png,jpg - 允许您将要删除的文件夹更改为您想要的文件夹,例如从C驱动器更改为图片

The Program

import glob,os,sys,re,datetime

os.chdir("C:\\Users\\") # ------> PLEASE CHANGE THIS TO PREVENT YOUR C DRIVE GETTING DESTROYED THIS IS JUST AN EXAMPLE
src = os.getcwd()#Scans src which must be set to the current working directory 
cn = 0
filedate = '2019'
clrd = 0
def random_function_name():
  print("No files match the given criteria!")
  return;

def find(path, *exts):
    dirs = [a[0] for a in os.walk(path)]
    f_filter = [d+e for d in dirs for e in exts]    
    return [f for files in [glob.iglob(files) for files in f_filter] for f in files]
print(src)
my_files = find(src,'\*py', '\*txt') #you can also add parameters like '\*txt', '\*jpg' ect
for f in my_files:
  cn += 1
  if filedate in datetime.datetime.fromtimestamp(os.path.getctime(f)).strftime('%Y/%m/%d|%H:%M:%S'):
    print(' | CREATED:',datetime.datetime.fromtimestamp(os.path.getctime(f)).strftime('%Y/%m/%d|%H:%M:%S'),'|', 'Folder:','[',os.path.basename(os.path.dirname(f)),']', 'File:', os.path.split(os.path.abspath(f))[1], ' Bytes:', os.stat(f).st_size)
    clrd += os.stat(f).st_size
  def delete():
    if cn != 0:
      x = str(input("Delete {} file(s)? >>> ".format(cn)))
      if x.lower() == 'yes':
        os.remove(f)
        print("You have cleared {} bytes of data".format(clrd))
        sys.exit()
      if x.lower() == 'no':
        print('Aborting...')
        sys.exit()
      if x != 'yes' or 'no':
        if x != '': 
          print("type yes or no")
          delete()
        else: delete()
    if cn == 0:
      print(str("No files to delete."))
      sys.exit()

delete()


if filedate not in datetime.datetime.fromtimestamp(os.path.getctime(f)).strftime('%Y/%m/%d|%H:%M:%S'):
  sys.setrecursionlimit(2500)
random_function_name()

On its own

这是为了将它应用于您自己的代码

    import glob,os,sys,re,datetime

    os.chdir('C:\\Users')
    src = os.getcwd()

    def find(path, *exts):
        dirs = [a[0] for a in os.walk(path)]
        f_filter = [d+e for d in dirs for e in exts]    
        return [f for files in [glob.iglob(files) for files in f_filter] for f in files]

    my_files = find(src,'\*py', '\*txt') #to add extensions do \*extension 
    for f in my_files:
      if filedate in datetime.datetime.fromtimestamp(os.path.getctime(f)).strftime('%Y/%m/%d|%H:%M:%S'):
        os.remove(f)
© www.soinside.com 2019 - 2024. All rights reserved.