簡體   English   中英

使用Python工作表中的名稱映射,借助Python腳本重命名文件夾中的文件名

[英]Rename the name of files in the folder with the help of Python Script, using name map from Excel sheet

文件夾中有許多CSV文件,我希望將其重命名。 有一個excel表,其中包含要重命名為文件夾的文件的名稱。

文件夾中的文件命名為

TestData_30April.csv
TestData_20April.csv
TestData_18April.csv etc

而excel表包含名稱為

0.25-TestData_30April
0.98-TestData_20April
0.33-TestData_20April etc

excel表中的第一行包含Header名稱,而wards上的第2行包含要重命名的文件名。

我的目標是重命名

TestData_30April.csv同樣適用於所有其他文件的0.25-TestData_30April.csv

這是代碼:

import os
import xlrd

#Excel Sheet containing name of files to be renamed in that folder
path="C:\\Users\\Desktop\\Test_Data\\Test_Summary.csv"

#Folder Containg all orginal file names
dir = "C:\\Users\\Desktop\\Wear_Data"

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))  

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 location'.format(name.split('-')[1]+'.csv')








Here is the error
    dir_file_name = os.path.join(path_to_folder,name.split('-')[1],'.csv')

IndexError: list index out of range

嘗試以下代碼:

for name in list_of_filename_in_excel:
    excel_file_name = os.path.join(path_to_folder, name,'.csv')
    newname = name
    if '-' in name:
        newname = name.split('-')[1]
    dir_file_name = os.path.join(path_to_folder,newname,'.csv' )

    if os.path.exists(dir_file_name):
        print('changing file name {} to {}'.format(newname,name))
        os.rename(dir_file_name, excel_file_name)
    else:
        print('no file {} with name found in location'.format(newname+'.csv')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM