65

我正在尝试编写一个 python 脚本来删除文件夹中早于 X 天的所有文件。这是我到目前为止所拥有的:

import os, time, sys
    
path = r"c:\users\%myusername%\downloads"
now = time.time()

for f in os.listdir(path):
  if os.stat(f).st_mtime < now - 7 * 86400:
    if os.path.isfile(f):
      os.remove(os.path.join(path, f))

当我运行脚本时,我得到:

Error2 - system cannot find the file specified,

它给出了文件名。我究竟做错了什么?

4

11 回答 11

31

os.listdir()返回一个裸文件名列表。这些没有完整路径,因此您需要将其与包含目录的路径结合起来。当您去删除文件时,您正在执行此操作,但不是在您删除文件时stat(或当您这样做时isfile())。

最简单的解决方案是在循环顶部执行一次:

f = os.path.join(path, f)

现在f是文件的完整路径,您可以f在任何地方使用(将您的remove()调用更改为也可以使用f)。

于 2012-09-18T22:06:54.520 回答
18

我认为新的pathlib与日期的箭头模块一起使代码更整洁。

from pathlib import Path
import arrow

filesPath = r"C:\scratch\removeThem"

criticalTime = arrow.now().shift(hours=+5).shift(days=-7)

for item in Path(filesPath).glob('*'):
    if item.is_file():
        print (str(item.absolute()))
        itemTime = arrow.get(item.stat().st_mtime)
        if itemTime < criticalTime:
            #remove it
            pass
  • pathlib使列出目录内容、访问文件特征(例如创建时间)和获取完整路径变得容易。
  • 箭头使计算时间更容易和更整洁。

这是显示pathlib提供的完整路径的输出。(无需加入。)

C:\scratch\removeThem\four.txt
C:\scratch\removeThem\one.txt
C:\scratch\removeThem\three.txt
C:\scratch\removeThem\two.txt
于 2017-01-17T19:00:41.557 回答
14

您还需要给它路径,否则它会在 cwd 中查找 .. 具有讽刺意味的是,您在其他地方做了,os.remove但没有其他地方......

for f in os.listdir(path):
    if os.stat(os.path.join(path,f)).st_mtime < now - 7 * 86400:
于 2012-09-18T22:02:52.370 回答
5

您需要使用if os.stat(os.path.join(path, f)).st_mtime < now - 7 * 86400:而不是if os.stat(f).st_mtime < now - 7 * 86400:

我发现使用os.path.getmtime更方便:-

import os, time

path = r"c:\users\%myusername%\downloads"
now = time.time()

for filename in os.listdir(path):
    # if os.stat(os.path.join(path, filename)).st_mtime < now - 7 * 86400:
    if os.path.getmtime(os.path.join(path, filename)) < now - 7 * 86400:
        if os.path.isfile(os.path.join(path, filename)):
            print(filename)
            os.remove(os.path.join(path, filename))

于 2019-03-01T12:10:17.943 回答
5

我以更充分的方式做到了

import os, time

path = "/home/mansoor/Documents/clients/AirFinder/vendors"
now = time.time()

for filename in os.listdir(path):
    filestamp = os.stat(os.path.join(path, filename)).st_mtime
    filecompare = now - 7 * 86400
    if  filestamp < filecompare:
     print(filename)
于 2020-08-12T08:28:04.240 回答
3

一个简单的 python 脚本,用于删除超过 10 天的 /logs/ 文件

#!/usr/bin/python

# run by crontab
# removes any files in /logs/ older than 10 days

import os, sys, time
from subprocess import call

def get_file_directory(file):
    return os.path.dirname(os.path.abspath(file))

now = time.time()
cutoff = now - (10 * 86400)

files = os.listdir(os.path.join(get_file_directory(__file__), "logs"))
file_path = os.path.join(get_file_directory(__file__), "logs/")
for xfile in files:
    if os.path.isfile(str(file_path) + xfile):
        t = os.stat(str(file_path) + xfile)
        c = t.st_ctime

        # delete file if older than 10 days
        if c < cutoff:
            os.remove(str(file_path) + xfile)

你可以用__file__你的路径替换。

于 2016-04-12T08:59:59.900 回答
1

这是我在 Windows 机器上的操作方法。它还使用 shutil 来删除在下载中创建的子目录。我也有一个类似的工具来清理我儿子电脑硬盘上的文件夹,因为他有特殊需要并且倾向于让事情快速失控。

import os, time, shutil

paths = (("C:"+os.getenv('HOMEPATH')+"\Downloads"), (os.getenv('TEMP')))
oneday = (time.time())- 1 * 86400

try:
    for path in paths:
        for filename in os.listdir(path):
            if os.path.getmtime(os.path.join(path, filename)) < oneday:
                if os.path.isfile(os.path.join(path, filename)):
                    print(filename)
                    os.remove(os.path.join(path, filename))
                elif os.path.isdir(os.path.join(path, filename)):
                    print(filename)
                    shutil.rmtree((os.path.join(path, filename)))
                    os.remove(os.path.join(path, filename))
except:
    pass
                
print("Maintenance Complete!")
于 2021-02-08T22:10:46.390 回答
1

有了推导,可以是:

import os
from time import time


p='.'
result=[os.remove(file) for file in (os.path.join(path, file) for path, _, files in os.walk(p) for file in files) if os.stat(file).st_mtime < time() - 7 * 86400]
print(result)
  • 使用 match = os.remove(file) 删除文件
  • 将所有文件循环到 path = for file in
  • 生成所有文件 = (os.path.join(path, file) for path, _, files in os.walk(p) for file in files)
  • p 是文件系统的目录
  • 验证 mtime 是否匹配 = if os.stat(file).st_mtime < time() - 7 * 86400

可能会看到:https ://ideone.com/Bryj1l

于 2020-01-20T22:41:37.963 回答
1

这将删除超过 60 天的文件。

import os

directory = '/home/coffee/Documents'

os.system("find " + directory + " -mtime +60 -print")
os.system("find " + directory + " -mtime +60 -delete")
于 2018-08-31T17:33:52.887 回答
0

其他一些答案也有相同的代码,但我觉得它们使一个非常简单的过程过于复杂

import os
import time

#folder to clear from
dir_path = 'path of directory to clean'
#No of days before which the files are to be deleted
limit_days = 10

treshold = time.time() - limit_days*86400
entries = os.listdir(dir_path)
for dir in entries:
    creation_time = os.stat(os.path.join(dir_path,dir)).st_ctime
    if creation_time < treshold:
        print(f"{dir} is created on {time.ctime(creation_time)} and will be deleted")
于 2021-04-21T14:07:55.660 回答
0

想添加我想出的来完成这项任务。该函数在登录过程中被调用。

    def remove_files():
        removed=0
        path = "desired path"
        # Check current working directory.
        dir_to_search = os.getcwd()
        print "Current working directory %s" % dir_to_search
        #compare current to desired directory
        if dir_to_search != "full desired path":
            # Now change the directory
            os.chdir( desired path )
            # Check current working directory.
            dir_to_search = os.getcwd()
            print "Directory changed successfully %s" % dir_to_search
        for dirpath, dirnames, filenames in os.walk(dir_to_search):
           for file in filenames:
              curpath = os.path.join(dirpath, file)
              file_modified = datetime.datetime.fromtimestamp(os.path.getmtime(curpath))
              if datetime.datetime.now() - file_modified > datetime.timedelta(hours=1):
                  os.remove(curpath)
                  removed+=1
        print(removed)
于 2017-01-17T17:23:24.337 回答