使用Excel工作表中的名称映射,借助Python Script重命名文件夹中文件的名称

时间:2019-05-13 05:03:13

标签: python xlrd

我要重命名的文件夹中有许多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')

1 个答案:

答案 0 :(得分:1)

Edit2: 根据excel文件示例,尝试以下代码:

if not request.json or not 'fac_name' in request.json:

旧答案

编辑: 下例中文件“ myfile.csv”的内容为:

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

如果您在读取文件时遇到问题,请首先确保它是csv格式的文件,并且可以在任何文本编辑器中打开它,如果仍然有问题,可以尝试使用encoding ='utf-8'打开​​它:

0.25-TestData_30April
0.98-TestData_20April
0.33-TestData_20April 

您可以根据您的excel文件(csv文件)尝试以下简单代码

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

已测试的输出:

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