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.
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: folders.remove(folder) 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.
- 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.
- extensions are the file extensions which you want to delete.
- 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.