Automating tasks in Python – Deleting files

I have decided to use Python for automating some tasks that I do regularly and which consume a lot of time.

I have started with deleting useless files from my code base. I have been using github as a backup for my codebase. I need to upload the files on github server. When I am programming in C many executables and object files(.exe and .o) are generated. I need to delete these everytime before I commit my code base to github because backing up these files is of no use to me.

My git repo containing the full script can be viewed here. I’ll keep it updated there. I am placing the code here also but no updates guaranteed here.

import os

cur = os.getcwd() + "\\..\\..\\..\\git_repo\\C\\"
extensions = ['.exe', '.o']
exclude = ['.git']

def delete_or_not(name):
    for i in extensions:
        if name.endswith(i):
            return True

    return False

def cur_files(files):
    for name in files:
        if delete_or_not(name):
            yield name

def main(startpath):
    for path, folders, files in os.walk(startpath, True):
        for folder in exclude:
            if folder in folders:

        for name in cur_files(files):
            os.remove(path + "\\" + name)main(cur)

The script is simple. The things that anyone would need to change are at the beginning. These are cur, extensions and exclude.

  1. cur is the path of the folder, in which you start deleting files, relative to the script. If you want to put absolute path you need to take out os.getcwd(). Files in its subfolders are also deleted.
  2. extensions are the file extensions which you want to delete.
  3. exclude are the folder which you want to exclude from this deletion script’s scope. Generally you would want the hidden folders to be excluded. I included one folder which I did not want the script to go through.

After making these changes you can simply double click to delete files if you have Python installed. I use Python 2 but this should be easy to convert to Python 3 also.

Next time I’ll make a script to run a group of Python scripts. That’ll help me to make any number of different scripts and choose what I need to run at different times like at startup, shutdown, before uploading files etc.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s