List 使用python大容量搜索/替换文件名
我有:List 使用python大容量搜索/替换文件名,list,python-2.7,xlrd,List,Python 2.7,Xlrd,我有: excel文件格式为A1:B2 包含200个jpeg文件的文件夹 我正在尝试使用列A中的值搜索文件夹中的文件名,如果在不更改文件夹中文件扩展名的情况下找到,则将其替换为列B中的值 在这里,我坚持使用各种滑橇来做这件事,但失败了。这是我的密码: import os import xlrd path = r'c:\users\c_thv\desktop\x.xls' #collect the files in fexceler path1 = r'c:\users\c_thv\desktop
列A
中的值搜索文件夹中的文件名,如果在不更改文件夹中文件扩展名的情况下找到,则将其替换为列B
中的值
在这里,我坚持使用各种滑橇来做这件事,但失败了。这是我的密码:
import os
import xlrd
path = r'c:\users\c_thv\desktop\x.xls'
#collect the files in fexceler
path1 = r'c:\users\c_thv\desktop'
data = []
for name in os.listdir(path1):
if os.path.isfile(os.path.join(path1, name)):
fileName, fileExtension = os.path.splitext(name)
if fileExtension == '.py':
data.append(fileName)
#print data
#collect the filenames for changing
book = xlrd.open_workbook(path)
sheet = book.sheet_by_index(0)
cell = sheet.cell(0,0)
cells = sheet.row_slice(rowx=0,start_colx=0,end_colx=2)
excel = []
#collect the workable data in an list
for cell in cells:
excel.append(cell)
#print excel
#compare list for matches
for i,j in enumerate(excel):
if j in data[:]:
os.rename(excel[i],data[i])
如果数据[:]:中有j,请尝试在之后打印“找到匹配项”
,以检查是否满足条件。我猜不会有匹配,因为列表中的数据
都是python文件名(如果fileExtension='.py'
),而您正在excel
列表中查找jpeg文件。
此外,old
未定义
编辑:
如果我理解正确,这将有助于:
import os, xlrd
path = 'c:/users/c_thv/desktop' #path to jpg files
path1 = 'c:/users/c_thv/desktop/x.xls'
data =[] #list of jpg filenames in folder
#lets create a filenames list without the jpg extension
for name in os.listdir(path):
fileName, fileExtension = os.path.splitext(name)
if fileExtension =='.jpg':
data.append(fileName)
#lets create a list of old filenames in the excel column a
book = xlrd.open_workbook(path1)
sheet = book.sheet_by_index(0)
oldNames =[]
for row in range(sheet.nrows):
oldNames.append(sheet.cell_value(row,0))
#lets create a list with the new names in column b
newNames =[]
for row in range(sheet.nrows):
newNames.append(sheet.cell_value(row,1))
#now create a dictionary with the old name in a and the corresponding new name in b
fileNames = dict(zip(oldNames,newNames))
print fileNames
#lastly rename your jpg files
for f in data:
if f in fileNames.keys():
os.rename(path+'/'+f+'.jpg', path+'/'+fileNames[f]+'.jpg')
它是怎么失败的?什么(没有)发生?@TimCastelijns:-没有任何变化。没有效果。我认为在比较两件事(清单)时会出现一些问题。我对重命名行不是很确定。如果我错了,请纠正我。@TimCastelijns我能用字典吗。?有没有办法从excel中创建dicts。?空白列表返回。很抱歉,
旧的
应该被替换excel
。编辑。如果文件扩展名为“.py”,请附加相应的文件名。应将其替换为data.append(glob.glob('*.py'))
。正当请复习一下。