[英]Python, Deleting all files in a folder older than X days
我正在嘗試編寫一個 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
,
它給出了文件名。 我究竟做錯了什么?
os.listdir()
返回一個裸文件名列表。 這些沒有完整路徑,因此您需要將其與包含目錄的路徑結合起來。 當你去刪除文件時你正在這樣做,但當你stat
文件時(或者當你執行isfile()
)。
最簡單的解決方案是在循環的頂部執行一次:
f = os.path.join(path, f)
現在f
是文件的完整路徑,您只需在任何地方使用f
(將您的remove()
調用更改為也僅使用f
)。
我認為新的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提供的完整路徑的輸出。 (無需加入。)
C:\scratch\removeThem\four.txt
C:\scratch\removeThem\one.txt
C:\scratch\removeThem\three.txt
C:\scratch\removeThem\two.txt
你需要給它的路徑也還是會看在CWD ..諷刺的是哪些是你自己的os.remove
,但沒有哪個地方...
for f in os.listdir(path):
if os.stat(os.path.join(path,f)).st_mtime < now - 7 * 86400:
你需要使用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))
我以更充分的方式做到了
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)
一個簡單的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__
您可以替換為您的路徑。
這將刪除超過 60 天的文件。
import os
directory = '/home/coffee/Documents'
os.system("find " + directory + " -mtime +60 -print")
os.system("find " + directory + " -mtime +60 -delete")
有了理解,可以是:
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)
可能會看到: https : //ideone.com/Bryj1l
這是我在 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!")
想添加我想出的東西來完成這項任務。 該函數在登錄過程中被調用。
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)
只有在空間不足時才刪除文件的腳本,這非常適合生產環境中的日志和備份。
如果未添加新備份,刪除舊文件最終將刪除所有備份
https://gist.github.com/PavelNiedoba/811a193e8a71286f72460510e1d2d9e9
其他一些答案也有相同的代碼,但我覺得它們使一個非常簡單的過程過於復雜
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")
另一種簡單的方法是利用 pathlib 和列表理解來刪除具有給定模式的文件。
from pathlib import Path
archive_path = "/dir/path/mi/archive"
file_pattern = "file-name-*.tar.gz"
files = [file for file in Path(archive_path).glob(file_pattern) if file.stat().st_mtime < now - 1 * 86400]
for file in files:
file.unlink()
我參加聚會可能有點晚了,但這是我使用 pathlib 的時間戳將日期對象轉換為浮點數並將其與 file.stat().st_mtime 進行比較的方法
from pathlib import Path
import datetime as dt
from time import ctime
remove_before = dt.datetime.now()-dt.timedelta(days=10) files older than 10 days
removeMe = Path.home() / 'downloads' # points to :\users\%myusername%\
for file in removeMe.iterdir():
if remove_before.timestamp() > file.stat().st_mtime:
print(ctime(file.stat().st_mtime))
file.unlink() # to delete the file
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.