How would I empty my linux trash from python?

Would I just do a simple os.remove? Or is there an easier way? I am also working on deleting all files within a directory, for multiple directories.

I have found this:

#!/usr/bin/env python             
import os

def nukedir(dir):
    if dir[-1] == os.sep: dir = dir[:-1]
    files = os.listdir(dir)
    for file in files:
        if file == '.' or file == '..': continue
        path = dir + os.sep + file
        if os.path.isdir(path):
            nukedir(path)
        else:
            os.unlink(path)
    os.rmdir(dir)

nukedir("/home/mb/test");

Recommended Answers

All 4 Replies

Thank you for the info, I will most likely use that for removing whole directories.

When testing this script, I just get my usage message spit back at me...do I have this scripted right? I'm also not sure if my FILE and TREE lists are setup correctly...

#!/usr/bin/env python

import os
import sys
import getopt
import shutil

HOME = '/home/eric'

FILES = ['/home/eric/.kde/share/apps/kaffeine/playlists/NEW.kaffeine', '/home/eric/.kde/share/apps/kcookiejar/cookies', '/home/eric/.kde4/share/apps/kcookiejar/cookies']

TREE = ['/home/eric/.kde4/share/apps/RecentDocuments/', '/home/eric/.kde/share/apps/RecentDocuments/', '/home/eric/.macromedia/Flash_Player/#SharedObjects/']

TRASH = '/home/eric/.local/share/Trash/'

def usage():
  print "Usage:"
  print "%s [-h <remove history>] [-t <empty's trash>] [-a <all>]" % sys.argv[0]

def main():
  try:
    opts, args = getopt.gnu_getopt(sys.argv[1:], "h:t:a")
  except getopt.GetoptError:
    usage()
    return

  for o, a in opts:
    if o == "-h":
      use_history = True
    if o == "-t":
      use_trash = True
    if o == "-a":
      use_all = True
      
  if use_history:
  	nukedirs(TREE)
	nukefiles(FILES)
  if use_trash:
     	nuketrash(TRASH)
  if use_all:
     	nukeall()

def nukefiles(files):
	os.remove(files)

def nukedirs(tree):
	shutil.rmtree(tree)

def nuketrash(trash):
	shutil.rmtree(trash)

def nukeall():
  	nukedirs(TREE)
	nukefiles(FILES)
	nuketrash(TRASH)

if __name__ == '__main__':
  main()

This part prints the usage blurb and exits if you don't include usage options on the command line. "h", "t", and "a" are the usage options and are directly below the quoted code.

def main():
  try:
    opts, args = getopt.gnu_getopt(sys.argv[1:], "h:t:a")
  except getopt.GetoptError:
    usage()
    return

I have been using the arguments for running the script. "python empty.py -t" which should empty the trash. Do I have to add the "-" in there?

def main():
  try:
    opts, args = getopt.gnu_getopt(sys.argv[1:], "-h:-t:-a")
  except getopt.GetoptError:
    usage()
    return
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.