DEV Community

Cover image for Rename and Delete files with Python
Lucas de Brito Silva
Lucas de Brito Silva

Posted on

Rename and Delete files with Python

Every day I find myself in need of doing tiring jobs that can be replaced by scripts and that the computer can help me too much, so one day I thought "Okay, I got tired, from now on I refuse to do that kind of work!" and from then on things only got better.

Since college, I created a great bond with the Python programming language, and we became great friends. That way I developed a script with him that would save my life!

Alt Text

In my work sometimes I needed to rename files from a list or even delete them from a folder, because they were no longer useful. So my first approach was to create two functions.

The first function was to rename files, so that they had a pattern and an order, like: file_1, file_2 and so on.

The heart of this code, as you can see, is in the os.rename that renames from the old name to the new file name.
NOTE: One very cool thing is that the script renames the whole way, so it makes use of the glob.

The second problem was that I needed to delete all files that were not on a .txt list (believe me, that list was over 100 files). So I used a very similar approach, but with the use of pandas, to read the txt file, of .index to try to find the file and os.remove to remove the files outside the list. The code is shown below.

And it's because of scripts like these that I have time today to write this article for you. I hope you like it and that it helped!

Top comments (0)