Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Clean Up Script
#1
Hi Everyone, I am new to Python and jumping into automating certain processes. Learning so much.

One of the scripts I am working on is figuring out how to remove folders/files from a network drive older then 2 days. Then having one sub set of folders remain for at least 14 days before removing them. I am able to go into the main folder and remove any file or folder older then 2 days. However trying to figure out the best way still for telling the script not to touch folderB until it is older the 14 days inside of testDirectory but remove folderA only every 2 days in testDirectory. I was thinking of using if else to further it but seem to be stuck here if that is the best route. Also wondering if I should do an overall for loop to go through every folder inside of testDirectory. Got this far and not giving up but curious if this script looks ok so far for the 2 days removal.

import os
import time
import shutil

two_days = 2
path =r"E:\testDirectory"
now = time.time()

for testFolder in os.listdir(path):
	if os.path.getmtime(os.path.join(path, testFolder)) < now - two_days * 86400:
		try:
			print(testFolder)
			for root, dirs, files in os.walk(os.path.join(path, testFolder), topdown=False):
				for fileName in files:
						os.chmod(os.path.join(root, fileName), 0o777)
						os.remove(os.path.join(root, fileName))
				for dirName in dirs:
						os.rmdir(os.path.join(root, dirName))
				os.rmdir(os.path.join(path, testFolder))
		except Exception as e:
				print ("error removing file/directory")
				print (e)
Reply
#2
Why not use shutil.rmtree() ?
Reply
#3
Do you mean specify in the script folderB and set that one to use shutil.rmtree or recommend I use the shutil module overall?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Can i clean this code ? BSDevo 8 954 Oct-28-2023, 05:50 PM
Last Post: BSDevo
  How to clean UART string Joni_Engr 4 2,503 Dec-03-2021, 05:58 PM
Last Post: deanhystad
  How to clean session mqtt SayHiii 0 2,010 Dec-09-2019, 07:56 AM
Last Post: SayHiii
  how to clean up unstarted processes? Skaperen 2 2,257 Aug-27-2019, 05:37 AM
Last Post: Skaperen
  sched.scheduler -> clean denisit 1 2,884 Nov-28-2018, 09:52 AM
Last Post: Gribouillis
  clean script by code fen1c5 8 4,702 Oct-16-2018, 05:11 AM
Last Post: volcano63
  clean up list elements and replace metalray 7 4,243 Aug-30-2018, 08:13 AM
Last Post: metalray
  Clean Data using NLTK disruptfwd8 0 3,338 May-12-2018, 11:21 PM
Last Post: disruptfwd8
  Clean up Code liamwemyss 1 3,373 Jun-07-2017, 08:36 PM
Last Post: Ofnuts
  Clean file with missing values Felipe 8 6,187 Jan-23-2017, 05:31 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020