Data Science

Data science for the business of fundraising.

walkfiles list

Python: Deleting Files with a Specific Extension

Very few things in life come close to the satisfaction that I get when closing out a project and deleting old files. I have been working on automating the deletion of some of my files to be more efficient and here is a quick cleanup python script that you can use too.

First, open your PowerShell or notebook, whichever you are comfortable working in. Then determine where the files that you want to delete are located, and determine if they are a specific type of file you want to delete. Now that you have an essential plan you can begin.

You will need to import a python package that identifies paths on your computer. The package is called Path, and you can pip install it by typing pip install path.py if you do not have it already. One thing I noted is that in some versions of python path you can use a lower case p. I am using Python3 and need to use an uppercase P.

Then you will need to define the location of the files that you are deleting. Here, I chose to define my function as d but you can call yours whatever you want. Then you will need to list the directory information where your files are located with your specific information. One thing to remember here is make sure you have your opening and closing quotes! I forgot that the first time I was trying this out.

d = Path('C:/Users/name/Desktop/Test_folder/')

Next, apply the method walkfiles to your path d.   For reference, the walk() method comes from the path  package and is able to generate file names in the tree directory on your computer. The purpose of applying this with the astrisk is that you are looking at all types of files. I like to then use a list to show all the files in the folder.

From there, I created a variable named files and assign it the method of walkfiles and only want to delete Excel files.

Then you will create a For Loop, which means python will process each line of and end with the print option. What the text is saying is in the files that are defined with the extension of .xsls, you are applying the remove method. Printing the files with the Excel extension will show that the correct things have been deleted.

Hope you enjoyed this quick script on deleting. Remember that if you implement this it will delete your files and not simply put them into your trash can!

To learn more about how the BWF Insight team uses analytics tools like  to help fundraisers all around the world, check us out on the web at BWF Insight.

Full article text is available via montko.com, 5/3/17.

,