'How to delete the contents within a folder without deleting the folder using python
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.
- Deleting a folder using shutil is actually deleting the Main folder b instead of the folder inside the b which start with CXP. Thanks for this stack over flow as i am learning and practicing from here.
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)
Solution 1:[1]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | molinav |
