A script to remove unneeded files The hard drive in my dev box is running out of space so I wrote this little script to try and free up space until I get a new drive.

My Concerns


Is the code pythonic?
Does the code go against any best practices?




import glob
import os
import psutil
import shutil

PATHS = ['/var/log/*', '/tmp/*', '/home/ricky/Downloads/']

USAGE = psutil.disk_usage('/').percent

if os.geteuid() != 0:
    exit("You need to have root privileges to run this script.")

def flatten(alist):
    if alist == []:
        return []
    elif type(alist) is not list:
        return [alist]
    else:
        return flatten(alist[0]) + flatten(alist[1:])

if __name__ == '__main__':
    for path in flatten(map(glob.glob, PATHS)):
        if os.path.isfile(path):
            os.remove(path)
        if os.path.isdir(path):
            shutil.rmtree(path)

    print "Usage Before {}\nUsage After {}".format(USAGE, psutil.disk_usage('/').percent)


Example Output:



ricky@ricky-OptiPlex-330:~/Projects/Python 
$ sudo python cleanup.py 
Usage Before 83.5
Usage After 82.1
Move your code inside a function rather than doing things at module level to make it re-useable. Your function could accept a list of paths either through a function call or through command line arguments instead of a global list of paths.
Keep standard library, third party imports separate.
You could use itertools.chain.from_iterable instead of your flatten function. Also use glob.iglob to get an iterator instead of list of files to save memory.

for path in chain.from_iterable(glob.iglob(path) for path in PATHS):
    ...

For comparing types use isinstance instead of comparing types using is. is won't work in case of multiple-inheritance. Read: Differences between isinstance() and type() in python