删除超过7天的文件

时间:2016-05-23 19:40:27

标签: python python-2.7

我看过一些帖子要删除特定文件夹中的所有文件(不是文件夹),但我根本就听不懂。

我需要使用UNC路径并删除超过7天的所有文件。

 Mypath = \\files\data\APIArchiveFolder\

有人有快速脚本,他们可以专门输入上面的路径,这将删除超过7天的所有文件?

3 个答案:

答案 0 :(得分:16)

此代码删除当前工作目录中> = 7天前创建的文件。自行承担风险。

import os
import time

current_time = time.time()

for f in os.listdir():
    creation_time = os.path.getctime(f)
    if (current_time - creation_time) // (24 * 3600) >= 7:
        os.unlink(f)
        print('{} removed'.format(f))

答案 1 :(得分:1)

另一个版本:

import os
import time
import sys

if len(sys.argv) != 2:
    print "usage", sys.argv[0], " <dir>"
    sys.exit(1)

workdir = sys.argv[1]

now = time.time()
old = now - 7 * 24 * 60 * 60

for f in os.listdir(workdir):
    path = os.path.join(workdir, f)
    if os.path.isfile(path):
        stat = os.stat(path)
        if stat.st_ctime < old:
            print "removing: ", path
            # os.remove(path) # uncomment when you will sure :)

答案 2 :(得分:0)

基于Vadim解决方案的更灵活的方法 请记住,void foo( std::mutex& m ) { while( true ) { { std::unique_lock<std::mutex> lock( m ); if( bar ) break; } // The mutex is now unlocked std::cout << "Hello World" << std::endl; std::this_thread::sleep_for( std::chrono::seconds( 1 ) ); } } 会删除该文件夹中X天之前的所有内容,因此请小心。

os.unlink(fileWithPath)