How to rename all the files in a folder using Python?

L. Wang
2 min readMay 7, 2021

I would like to share some files in a folder with others. However, there is some confidential information, more specifically some ID numbers, in the file names. Therefore, I need to remove these ID numbers from these file names.

The problem is that there are hundreds of these files. It is impossible (or too time-consuming) to rename these files manually.

I decided to use Python to complete this tedious task.

First, I need to separate the basename from the extension in the file name filename.

splitFilenames = os.path.splitext(filename)

Then, I need to remove numbers from the file basename basename, which is a string. There are several ways to do it. I choose the following method by using join and isdigit():

newbase = ''.join([i for i in basename if not i.isdigit()])

The final step is to rename the old filename oldFilename with the new filename newFilenameby using os.rename:

os.rename(oldFilename, newFilename)

I just need to enumerate all the file names in my directory to the files and I remove the numbers from each file name as described above. I use the following to enumerate the file names in my directory mydir :

--

--

L. Wang
L. Wang

Written by L. Wang

0 Followers

Data scientist, statistician

No responses yet