In this article, I would like to show you how you can rename the files in a directory using python.
Let us say we have list of files in a directory where the names are filled with some numbers in the middle randomly.
List of all files are in the path of C:\Users\admin\Desktop\files.
– che424324mistry.txt
– datasci3749283ence.txt
– de234vop345s.txt
– dock315435er.txt
– grad234uate14s.txt
– naturalla32434ng41uage.txt
– ph4334ysi41234cs.txt
– py234tho433n.txt
– statist34ics.txt
– webscrap2343ing.txt
Now we need to modify the names of those files by removing the numbers like below.
– chemistry.txt
– datascience.txt
– devops.txt
– docker.txt
– graduates.txt
– naturallanguage.txt
– physics.txt
– python.txt
– statistics.txt
– webscraping.txt
Let us start by importing the required string and OS modules.
import string import os
Creating the function named rename_files in which we are going to use below 2 functions.
- maketrans function
- translate function
for file in x:
os.rename(file,file.translate(file.maketrans('','','0123456789')))
Y=os.listdir(r'C:\Users\admin\Desktop\files')
print('\nList of all Renamed Files:\n\n\t',*Y,sep='\n- ')
Below is the complete Code:
import string
import os
def rename_files():
x=os.listdir(r'C:\Users\admin\Desktop\files')
print('List of all Located Files from the given path of ',os.getcwd())
print('\n',*x, sep='\n- ')
path=os.getcwd()
print("\nFrom the given Path:\n\n\t",path)
os.chdir(r'C:\Users\admin\Desktop\files')
for file in x:
os.rename(file,file.translate(file.maketrans('','','0123456789')))
Y=os.listdir(r'C:\Users\admin\Desktop\files')
print('\nList of all Renamed Files:\n\n\t',*Y,sep='\n- ')
Output:
