jfgdf 发表于 2017-3-13 14:02:33

python脚本删除n天之前的文件

管理Linux经常用到python脚本,然后写了脚本后,经常为了生成的文件占用磁盘空间而犯愁,这些写个函数以方便以后使用:


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
def rmdaybefore(pfile, days):
    """
    Delete pfile diectory days before files below
    :param pfile: local path
    :param days: before days
    :return: a list os.listdir pfile
    """
    d = 0
    try:
      d = int(days)
    except ValueError,e:
      print "You input the parameters of the days cannot be converted to int."
      sys.exit(1)
    BEDAYS = time.time() - (24 * 60 * 60 * d)
    if os.path.isdir(pfile):
      for f in os.listdir(pfile):
            fname = pfile + os.sep + f
            if os.path.isfile(fname):
                fmtime = os.path.getmtime(fname)
                if fmtime <= BEDAYS:
                  os.remove(fname)
                  return os.listdir(pfile)
    else:
      "You input the parameters of the pfile is not a directory."
      sys.exit(1)
if __name__ == '__main__':
    pfile = r"C:\\Users\\XXX\\Desktop\\html\\"
    for f in rmdaybefore(pfile,0.2):
      print f






页: [1]
查看完整版本: python脚本删除n天之前的文件