title: Delete Old directories in Python
body: <p>I have several directories and I want directories over 7 days old to be deleted. I have code already implemented but It doesn't seem to be working. Can anyone see where I am going wrong?</p>
  
  <pre><code>def delete_sandbox():
  
      for directories in os.listdir(os.getcwd()): 
  
          if not os.path.isdir(directories) or not os.stat(directories).st_ctime &lt; time.time()-(7*24*3600): 
              continue
          os.chdir(directories)
          drop_sandbox()
          os.chdir(rootDir)
          os.system("sudo rm -rf "+directories)
          print 'Folders older than 7 days old dropped and removed'
  </code></pre>
  
  <p>Thanks for any help</p>
  
  <p>The folders sandboxes drop but do not delete. I want the program to go into each one of these folders, drop the sandbox, chnage back to the root directory and delete all the old directories. When I do this the folders still exist.</p>
  
  <p>Also this function worked when I had the directories deleted by the string date stored in the folder name. But now that I am trying to get the timestamp it has stopped working.</p>
  
  <p>I have tested the <code>'rm -rf'+directories</code> and it does not delete old folders. When I try <code>shutil.rmtree</code> I get the error message: </p>
  
  <pre><code>Traceback (most recent call last):
    File "yep.py", line 21, in &lt;module&gt;
      delete_sandbox()
    File "yep.py", line 18, in delete_sandbox
      shutil.rmtree(directories)
    File "/home/build/workspace/downloads/Python-2.6.4/Lib/shutil.py", line 208, in rmtree
      onerror(os.listdir, path, sys.exc_info())
    File "/home/build/workspace/downloads/Python-2.6.4/Lib/shutil.py", line 206, in rmtree
      names = os.listdir(path)
  OSError: [Errno 2] No such file or directory: 'Debug'
  </code></pre>
  
  <p>Is there any other way to delete these folders?</p>
  
  <p>I got it working, I used <code>shutil.rmtree</code> and all seemed to worked. Thanks for any help. The amended code is:</p>
  
  <pre><code>def delete_sandbox():
  
      for directories in os.listdir(os.getcwd()): 
  
          if not os.path.isdir(directories) or not os.stat(directories).st_ctime &lt; time.time()-(sbox_age): 
              continue
          os.chdir(directories)
          drop_sandbox()
          os.chdir(rootDir)
          shutil.rmtree(directories)
          print 'Sandboxes older than 7 days old dropped and removed'
  
  delete_sandbox()
  </code></pre>