python - 在列表中查找文件的名称并使用列表中的索引重命名该文件
问题描述
这里是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中)
解决方案
假设您的代码正在运行并且您需要减少其大小和复杂性,这里是另一个版本。
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))
推荐阅读
- python - 用 pyplot 绘制二维数组
- mysql - 从 csv 文件导入数据库,utf8 问题
- php - jquery-uniform 单选按钮不起作用 yajra-laravel-datatable 包(laravel 5.6)
- jquery - Dropzone jquery - 始终使用 GET 请求,事件设置为 POST
- angular - 使用 angular5 在验证中未收到错误消息
- assembly - IAR 汇编器指令 IF
- python - 在 Python 2.7.1 中创建 unicode XML 文件
- javascript - 当用户完成输入时运行 JS 代码
- asp.net-mvc - ASP.NET MVC 5,在 Session 中存储列表值
- node.js - Firebase 云功能脚本未运行