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

  1. Is the code pythonic?
  2. 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]
        return flatten(alist[0]) + flatten(alist[1:])

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

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

Example Output:

$ sudo python cleanup.py 
Usage Before 83.5
Usage After 82.1
  • 4
    \$\begingroup\$ Why not just do sudo rm -rf /var/log/* /tmp/*? \$\endgroup\$ Aug 27 '17 at 22:44
  • \$\begingroup\$ codereview.stackexchange.com/users/9357/200-success This will work on Windows Mac and Linux \$\endgroup\$ Aug 27 '17 at 22:51
  • 2
    \$\begingroup\$ Windows has rd /s /q. \$\endgroup\$ Aug 27 '17 at 22:54
  • \$\begingroup\$ Note that your code will quite possibly break some daemons and logging. This is bad code not in terms of style but in terms of how it does what it does. \$\endgroup\$
    – Gnudiff
    Aug 29 '17 at 12:34
  • \$\begingroup\$ /tmp directory sometimes contains files that are USED by system as it runs. Logging function of some daemons will break if you just remove the files they write to. Logfile sizes are controlled using rotate logs and similar daemons. /tmp directory is usually emptied by system as you reboot. \$\endgroup\$
    – Gnudiff
    Aug 29 '17 at 12:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.