首页 > 解决方案 > 在列表中查找文件的名称并使用列表中的索引重命名该文件

问题描述

这里是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 notebook中)

标签: python

解决方案


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

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


推荐阅读