【问题标题】:How to delete files from a folder based on Date modified如何根据修改日期从文件夹中删除文件
【发布时间】:2017-09-13 16:09:43
【问题描述】:

我正在尝试根据修改日期从文件夹中删除文件,文件夹内的文件修改日期如下:

Name          Date modified

File 1      9/12/2017 1:34 PM
File 2      9/12/2017 1:38 PM
File 3      9/12/2017 12:00 PM
File 4      9/12/2017 12:00 PM
File 5      9/12/2017 7:40 AM
File 6      9/12/2017 7:40 AM

假设我只想将文件保留在这个文件夹中只有 30 分钟的时间,现在就说现在是下午 1:48,所以我希望在运行将删除文件的清理脚本后保留超过 30 分钟的将是:

Name          Date modified

File 1      9/12/2017 1:34 PM
File 2      9/12/2017 1:38 PM

提前致谢。

【问题讨论】:

    标签: python datetime path directory


    【解决方案1】:

    你可以试试这样的:

    import os
    import time
    
    now = time.time()
    
    folder = '<folder_path>'
    
    files = [os.path.join(folder, filename) for filename in os.listdir(folder)]
    for filename in files:
        if (now - os.stat(filename).st_mtime) > 1800:
            command = "rm {0}".format(filename)
            subprocess.call(command, shell=True)
    

    time.time() 以秒为单位返回实际时间。

    os.stat(filename).st_mtime 返回上次修改的时间,以秒为单位。

    1800 是以秒为单位的 30 分钟。

    【讨论】:

    • 感谢您在思考这个问题时提供的帮助,我能够做出适当的更改并且它现在可以满足我的需求!
    【解决方案2】:

    请参阅this。 一旦您知道如何修改日期,请将其与您当前的系统时间进行比较并根据需要删除。 如果您需要其他帮助,请告诉我。 抱歉,这应该是一个评论,但我还没有足够的代表:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-07
      相关资源
      最近更新 更多