在列表中查找文件名,并使用列表中的索引重命名该文件



python新手,我试图从excel文件中获取文件名列表(.wav(,在某个目录下找到具有这些名称的文件,并根据列表中的索引重命名这些wav文件。这是我的代码的简单版本:

import glob
import pandas as pd
import os
path_before = ""
path_after = ""
path_excel = ""
# the excel file with the names ("Title") of the wav files, I want to save the file name + extension
data = pd.read_excel(path_excel+"data.xlsx")
data['Title_temp'] = data['Title']+'.wav'
filelist = data['Title_temp']
# finding the wav files to be renamed 
file_names_all = glob.glob(path_before+'*')
# and get rid of the directory to just keep the names
get_name = []
for file in file_names_all:
temp_name = file.split('\')
get_name.append(temp_name[-1])
# for the wav files to be renamed, go through the filelist from the excel file
# and if the name is on filelist, rename it to the index of filelist, 
# so the new name should be a number.wav 
# Also, all the file names are in the list and they all should be renamed, 
# but I couldn't find a better way to do this, so the code below
for filename in get_name:
if filename in filelist:
try:
os.rename(filename, filelist.index(filename))
except:
print ('File ' + filename + ' could not be renamed!')
else: print ('File ' + filename + ' could not be found!')    

我打印出了目录和excel列表的文件名,它们匹配(与.wav扩展名和所有扩展名匹配(,但当我运行代码时,我总是收到找不到文件名的错误。有人能告诉我怎么了吗?(代码写在windows jupyter笔记本中(

假设您的代码正在运行,并且需要减少其大小和复杂性,这里是另一个版本。

import pandas as pd
import os
path_before = "path to the files to be renamed"
path_excel = "path to the excel file"
data = pd.read_excel('{}/data.xlsx'.format(path_excel))
files_to_rename = os.listdir(path_before)
for index, file_title in enumerate(data['Title']):
try:
# as per your code, the excel file has file names without extension, hence adding .wav extension in formatted string'
if '{}.wav'.format(file_title) in files_to_rename:
os.rename(os.path.join(path_before, '{}.wav'.format(file_title)), os.path.join(path_before, '{}.wav'.format(index)))
else:
print("File {}.wav not found in {}".format(file_title, path_before))
except Exception as ex:
print("Cannot rename file: {}".format(file_title))

最新更新