我有一个包含图像的文件夹,当前使用一些随机图像编号命名。我想用我放在数据框上的 Excel 工作表的特定列重命名目录中的所有图像。
注意:图像的随机数是excel值的最后部分。例如,如果文件夹中的图像名称为“img1097”,那么在 Excel 工作表中我可以在“First_Second_img1097”列中找到该图像。因此,在文件夹中,我有名称为“img1098”、“img1099”等的图像,在数据框中,我有如下值:
#my_dataframe
**Column**
First_Second_img1097
Table_Chairs_img1098
Cat_Image_img1099
我一直在尝试实施不同的选择,但没有成功。这是我的代码:
import os,re
path = r'myfolder\user\allimages\Main\target'
files = os.listdir(path)
for index, file in enumerate(files):
tempname = file.split('.')[0] #no extentions
for i in tempname :
for picture_name in my_dataframe['Column']:
if temp_file_name == picture_name:
os.rename(os.path.join(path, file),
os.path.join(path,str(index) + '.jpg'))
我期待一个答案,我将能够使用数据框的“列”列的单元格值重命名所有匹配的图像。因此“img1097”应重命名为“First_Second_img1097”。希望这可以清楚地说明。
这将解决您的问题:
import ntpath
import os,re
path = r'myfolder\user\allimages\Main\target'
pathlist = []
for root, dirs, files in os.walk(path):
for name in files:
pathlist.append(os.path.join(root, name))
for new_path in pathlist:
file_name = ntpath.basename(new_path)
tempname = file_name.split('.')[0]
for index, row in df["Columns"].iteritems():
new_row = row.split('_')[-1] ## Gives img1097
new_tempname = tempname.replace(" ", "") ## makes img 1097 to img1097
if new_row == new_tempname: ## Now the matching will work
os.rename(os.path.join(path, file_name), os.path.join(path, str(row)+'.jpg'))
要重命名目录中的所有图像文件,您可以尝试以下 python 程序。只需运行 python 脚本,文件就会根据 Excel 单元格值自动重命名:
import pandas as pd
import xlrd
import os
import glob
# Your directory
mydir = (os.getcwd()).replace('\\','/') + '/'
# Get data of cells from excel
df=pd.read_excel(r''+ mydir +'test.xlsx')
for i in range(len(df['Name'])):
print( df['Name'][i])
number_of_cell=len(df['Name'])
# Get the list of specified files in a directory
filelist=os.listdir(mydir)
for file in filelist[:]: # filelist[:] makes a copy of filelist.
if not(file.endswith('.png') or file.endswith('.jpg')):
filelist.remove(file)
print (filelist)
number_of_files=len(filelist)
# Rename all files in directory with a value of cell in excel
for i in range(number_of_files):
os.rename(mydir+ filelist[i], mydir+ df['Name'][i] + '.' + os.path.splitext(filelist[i])[1][1:])
print ('Success')
====已编辑====
import pandas as pd
import xlrd
import os
import glob
# Your directory
mydir = (os.getcwd()).replace('\\','/') + '/'
# Get data of cells from excel
df=pd.read_excel(r''+ mydir +'Book1.xlsx')
for i in range(len(df['New_Image_Name'])):
print( df['New_Image_Name'][i])
number_of_cell=len(df['New_Image_Name'])
# Get the list of specified files in a directory
filelist=os.listdir(mydir)
for file in filelist[:]: # filelist[:] makes a copy of filelist.
if not(file.endswith('.png') or file.endswith('.jpg')):
filelist.remove(file)
print (filelist)
number_of_files=len(filelist)
# Rename all files in directory with a value of cell in excel
# Files will be ranamed with cell value if the digits of last name of file is matched with the last digits in excel cell
for i in range(number_of_files):
for n in range(number_of_cell):
if ((((df['New_Image_Name'][n].split('_'))[len((df['New_Image_Name'][n].split('_')))-1]).split('.'))[0] == (((filelist[i].split('_'))[len((filelist[i].split('_')))-1]).split('.'))[0]):
os.rename(mydir+ filelist[i], mydir+ df['New_Image_Name'][n] + '.' + os.path.splitext(filelist[i])[1][1:])
break
print ('Success')
前后所有图片的文件名:
谢谢您的回答。上帝拯救你。