Python删除文件夹中旧文件

该段代码使用与windows与Linux,同时可以学习time的相关操作,以及time的格式转换

# coding:utf-8

import os
import time
import shutil


# %Y  Year with century as a decimal number.
# %m  Month as a decimal number [01,12].
# %d  Day of the month as a decimal number [01,31].
# %H  Hour (24-hour clock) as a decimal number [00,23].
# %M  Minute as a decimal number [00,59].
# %S  Second as a decimal number [00,61].
# %z  Time zone offset from UTC.
# %a  Locale's abbreviated weekday name.
# %A  Locale's full weekday name.
# %b  Locale's abbreviated month name.
# %B  Locale's full month name.
# %c  Locale's appropriate date and time representation.
# %I  Hour (12-hour clock) as a decimal number [01,12].
# %p  Locale's equivalent of either AM or PM.
# Thu Jan 28 14:03:39 2021

def remove_file_detail(path, diff_time):       # path  D:\Package\test1\cc.txt
    ctime = time.ctime(os.stat(path).st_ctime)  # 获取文件创建时间  time of last change
    atime = time.ctime(os.stat(path).st_atime)  # 获取文件创建时间  time of last access
    mtime = time.ctime(os.stat(path).st_mtime)  # 获取文件创建时间  time of last modification
    # print(ctime)  #Tue Jan 26 17:39:04 2021
    timestring = time.strptime(ctime, "%a %b %d %H:%M:%S %Y")  # 根据ctime的输出格式写出format字符串格式
    # print(timestring)   #time.struct_time(tm_year=2021, tm_mon=1, tm_mday=28, tm_hour=14, tm_min=3, tm_sec=45, tm_wday=3, tm_yday=28, tm_isdst=-1)
    timemiao = time.mktime(timestring)  # 将时间班变成秒数
    # print(timemiao)   #1611653944.0
    now = time.time()  # 获取当前时间的秒
    # print(now)  #1611814750.68371
    diff = now - timemiao  # 当前时间的秒数和文件创建时候想对比
    # print(diff)
    # 如果创建时间大于diff_time,删除该文件
    if diff > diff_time:
        print("delete the file: ", path)  # path = D:\Package\test1\re1.txt
        if os.path.exists(path):
            if os.path.isfile():
                os.remove(path)
            elif os.path.isdir(path):
                shutil.rmtree(path)  # 删除当前文件夹下所有文件和和子文件夹


def remove_file():
    path = r"D:\Package\test1"
    items = os.listdir(path)
    # print(items)
    for n in items:
        p = path + "\\" + n
        print(p)
        diff_time = 60 * 60 * 24 * 7 * 365 #根据自己需求定义时间间隔,这里定义是一年
        remove_file_detail(p, diff_time)

if __name__ == '__main__':
    remove_file()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值