在 Python 脚本的帮助下重命名文件夹中的文件名,使用来自 Excel sheet 的名称映射

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

我想重命名的文件夹中有很多CSV 文件。有一个 excel sheet 包含要重命名为文件夹的文件的名称。

文件夹中的文件命名为

TestData_30April.csv

TestData_20April.csv

TestData_18April.csv等

而 excel sheet 包含名称为

0.25-TestData_30April

0.98-TestData_20April

0.33-TestData_20April 等等

我的目标是重命名

"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.xlsx"

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

编辑2: 根据 excel 文件示例,尝试以下代码:

import os 
with open('myfile.csv', encoding='utf-8') as f:
    buff = f.read()

buff = buff.splitlines()[1:]

for data in buff:
    data = data.split(',')
    old_name, new_name = data[21] + '.csv', data[23] + '.csv'

    if os.path.exists(old_name):
        print('changing file name {} to {}'.format(old_name,new_name))
        os.rename(old_name, new_name)
    else:
        print('no file {} with name found in location'.format(old_name))

旧答案

编辑: 以下示例中文件 "myfile.csv" 的内容是:

0.25-TestData_30April
0.98-TestData_20April
0.33-TestData_20April 

如果您在读取文件时遇到问题,请首先确保它是一个 csv 格式的文件,您可以在任何文本编辑器中打开它,如果仍然有问题,您可以尝试使用 encoding=[=28 打开它=]:

with open('myfile.csv', , encoding='utf-8') as f:
        file_names = f.read().split()

你可以根据你的 excel 文件是 csv 文件来尝试这个简单的代码

import os

with open('myfile.csv') as f:
    file_names = f.read().split()

for name in file_names:
    new_name = name + '.csv'
    old_name = name.split('-')[-1] + '.csv'
    if os.path.exists(old_name):
        print('changing file name {} to {}'.format(old_name,new_name))
        os.rename(old_name, new_name)
    else:
        print('no file {} with name found in location'.format(old_name))

测试输出:

changing file name TestData_30April.csv to 0.25-TestData_30April.csv
no file TestData_20April.csv with name found in location
no file TestData_20April.csv with name found in location