This is my first question here on Stack overflow. I am very new in programming area and after going though some of the videos and links, I start to write my python program which I learn from google.
Here I am trying to run a program where I need to delete the folder in particular path(Starting with name CXP) which is 7 days old.
But here is two problems.
import os, time
import shutil
dir_name = os.path.expanduser("") + "/proj/a/b/"
test = os.listdir(dir_name)
now = time.time()
print(test)
for fname in os.listdir(dir_name):
if fname.startswith("CXP"):
folderstamp = os.stat(os.path.join(dir_name, fname)).st_mtime
foldercompare = now - 7 * 86400
if folderstamp < foldercompare:
shutil.rmtree(dir_name)
Your script is deleting the main folder because this is what is implemented. Note that you are doing checks based on fname
, but later use shutil.rmtree(dir_name)
if the condition is met. You need to correct the argument given to shutil.rmtree
:
import os
import time
import shutil
dir_name = os.path.expanduser("") + "/proj/a/b/"
test = os.listdir(dir_name)
now = time.time()
print(test)
for fname in os.listdir(dir_name):
if fname.startswith("CXP"):
folder = os.path.join(dir_name, fname)
folderstamp = os.stat(folder).st_mtime
foldercompare = now - 7 * 86400
if folderstamp < foldercompare:
shutil.rmtree(folder)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.