Python script for automating file rename

Abhishek Mishra
1 min readFeb 12, 2021

I had to rename files under a given directory , with names given as a header file. Here is the sample script

import os
import shutil
zip_location = input("enter file location:")
hdr_file_name = input("enter header file: ")
f = open(zip_location+"\\"+hdr_file_name, "r")
command_string = str(f.readline()).split("{EOL}")
#cleaning the command list
def command_clean(command_string):
for i in command_string:
if (i == "" ):
command_string.remove(i)
#cleaning up file name
def clean_file_name(name):
name = name.replace('"', "")
print("finale file name : ", name)
return name
#creating a copy of the specified file and renaming it
def copy_rename(file_name, file_to_name):
file_path = zip_location + "\\" #file location where it will be renamed and stored.
os.rename(file_path + file_to_name, file_path + file_name) #doubt : should i include the file extension
#extracting and separating the file name and file to be renamed (delimiter is the | symbol)
def command_extract(command_string):
for s in command_string:
sep = s.split("|")
cmd1 = sep[0].split("\\")[-1]
cmd2 = sep[1] #file to be renamed
file_name = clean_file_name(cmd1)
copy_rename(file_name,cmd2)
command_clean(command_string)
command_extract(command_string)

This is a simple python script which just takes two parameter.
1. The directory of the folder in which the file to be renamed is present
2. The header file which contains ‘|’ separated information such as new name for the file and corresponding file to be renamed.

--

--

Abhishek Mishra

I am a university student and have a zeal to learn.