Anand Patil
Anand Patil

Reputation: 37

Rename files in a folder using Python, using name map from Excel

There are many CSV files in a folder which I want to renamed. There is an excel sheet which contains name of files to be renamed to folder.

The files in folder are named as

TestData_30April.csv

TestData_20April.csv

TestData_18April.csv etc

while the excel sheet contains the name as

0.25-TestData_30April.

0.98-TestData_20April

0.33-TestData_20April

My Aim is to rename

"TestData_30April.csv" to "0.25-TestData_30April.csv"

similarly

"TestData_20April.csv" to "0.98-TestData_20April" etc.

my Problem Defination is similar to this one Here is the link "Rename files with Python, using name map from Excel"

Kindly and Please Help i am new to python.

Here is the Code and its not working

import os

import xlrd

**#Excel Sheet containing name of files to be renamed in that folder**

path="C:\\Users\\Desktop\\Test_Data\\Test_Summary.xlsx"

wb = xlrd.open_workbook(path) 

sheet = wb.sheet_by_index(0)

sheet.cell_value(0, 0)

**#In excel sheet column X or col_values(23) contains the file name to be renamed**

print(sheet.col_values(23))  

new_names = sheet.col_values(23)

for new_name in sheet.col_values(23):



if '-' in new_name:

    old_name = new_name.split("-")[1]

    if os.path.isfile(os.path.join(dir, old_name)):

        os.rename(os.path.join(dir, old_name), os.path.join(dir, new_name))

Kindly help i am new to python

Upvotes: 2

Views: 2320

Answers (2)

sahasrara62
sahasrara62

Reputation: 11228

list_of_filename_in_folder = [] # name of the files in the folder
list_of_filename_in_excel = [] #name of the files in excel

path_to_folder = ''  # base path of folder  

for name in list_of_filename_in_excel:
    excel_file_name = os.path.join(path_to_folder, name,'.csv')
    dir_file_name = os.path.join(path_to_folder,name.split('-')[1],'.csv' )
    if os.path.exists(dir_file_name):
      print('changing file name {} to {}'.format(name.split('-')[1],name))
      os.rename(dir_file_name, excel_file_name)
    else:
      print('no file {} with name found in project location'.format(name.split('-')[1]+'.csv')

Upvotes: 2

spzhu
spzhu

Reputation: 9

The filenames in you excel sheet do not contain the extension .csv, therefore the old_name is the filename without extension, while os.path.isfile checks the full filename and only returns true when filename and extension are all match.

Append the extension to your excel sheet and try again, it should work.

0.25-TestData_30April.csv
0.98-TestData_20April.csv
0.33-TestData_20April.csv

Upvotes: 0

Related Questions