tags:

views:

77

answers:

3

Hello,

I am creating several directories a day. After seven days I am going to drop a sandbox in these directories and delete them. I use a time stamp to name them. I have got some code below to show you what I have got.

today = datetime.date.today() # Today's date Binary
todaystr = datetime.date.today().isoformat() # Todays date as a string
minus_sevent = today - datetime.timedelta(days = 7) # 7 days ago as a string
minus_seven = minus_sevent.isoformat()
old_folders = minus_seven + '*'
def delete_sandbox():

    if os.path.exists(old_folders):
        os.chdir(old_folders)
        mks_drop_sandbox()
        os.chdir(rootDir)
        for filename in glob.glob(old_folders):
            shutil.rmtree(old_folders)
        print 'Sandboxes from 7 days ago removed'

if __name__ == '__main__': myObject = delete_sandbox()

This was similar code I used before to drop a sandbox and delete a one directory. But there may be several builds done in the days and I want to know how to enter each folder and do these tasks.

Folders in the directories will be created with their time as well as their date, I have variables that just remove all folders of a set date regardless of time.

Thanks

+3  A: 

old_folders = minus_seven + '*'

This does not do what you think it does. This gives you the name of a folder that literally ends in a *. Later, os.path.exists() will return False.

What you need to do is loop through the directories:

for d in os.listdir(os.getcwd()):
    if not os.path.isdir(d) or not d.startswith(minus_seven):
        continue
    # Do what you need to with 'd' here.

or as a list comprehension:

minus_seven_dirs = [d for d in os.listdir(os.getcwd())
    if os.path.isdir(d) and d.startswith(minus_seven)]

Basically, you can't feed os functions a list and expect them to do the right thing. They work on paths one at a time.

Mike D.
A: 

" I want to know how to enter each folder"

Are you asking about os.path.join to create the full path name?

http://docs.python.org/library/os.path.html#os.path.join

or os.chdir to change the working directory?

http://docs.python.org/library/os.html#os.chdir

S.Lott
A: 

You have two options:

Use os.walk

for root, dirs, files in os.walk('your root'):
for dir in dirs:
        os.chdir(os.path.join(root, dir))
        delete_sandbox()

Use os.path.walk then change delete_sandbox to be used as the callback.

def delete_sandbox(arg, dirname, names):
thanos