How to rename files in a directory using Python – (Solved)

Hello All,

 

I got myself coding using Python . Its really a great tool and wanted to share some of things I have been doing while mastering this tool.
Scenario –

I am collecting data from twitter and unfortunately got my filename wrong. There were around 750 files in the folder and manually changing the name is cumbersome , that is where python helped me do this task in minutes . Although took me a while to write this code and learn on the way. Wanted to post my findings and hope it helps you out. Will be commenting each steps so that you understand what is going on.

 

Code.

 

#!/anaconda3/bin/python

#Importing libraries

import string

import os

 

#Checking the current path
current_path = os.getcwd()

print(current_path)

#Getting all the files in the directory for the renaming

file_list = os.listdir()

#Storing the file path to be used in the for loop below

file_path =’/Users/jethin/Google_Drive/Capstone/Data_Extraction/ETH’

#Loop to iterate through all the files in the file_list variable stored above

for file_name in file_list:
old_file = os.path.join(file_path,file_name)
new_name = file_name.replace(“Bitcoin”,”Ethereum”)
new_file = os.path.join(file_path,new_name)
os.rename(old_file,new_file)
 

Bonus :

I tried many other of replace functions and using maketrans. This is the method that I was able to successfully replace. I tried without the filepath and gave me file not found. As soon as I added the filepath , it worked as a charm. In the for loop I have the old_file and the new file with the name change. The rename function helped me rename the file.

At times you may still find issues running this command. If so please check your permissions as that would be the only case from stopping you from renaming the file. If you are MAC or Linux user , use chmod -R 777. You can find more information on the same if not leave a comment.

 

Thanks

Jethin Abraham

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s