首页 > 解决方案 > 在 Python 脚本的帮助下,使用 Excel 表中的名称映射重命名文件夹中的文件名

问题描述

我要重命名的文件夹中有许多 CSV 文件。有一个 Excel 表,其中包含要重命名为文件夹的文件的名称。

文件夹中的文件命名为

TestData_30April.csv

TestData_20April.csv

TestData_18April.csv 等

而 excel 表包含的名称为

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

标签: pythonxlrd

解决方案


Edit2:根据 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='utf-8' 打开它:

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

推荐阅读