散装搜索/替换使用python
问题描述:
文件名我有:散装搜索/替换使用python
- Excel文件为A1:B2。
- 一个包含200个jpeg文件的文件夹。
我试图与价值搜索文件名的文件夹中Column A
如果发现不改变文件的扩展名的文件夹中,在Column 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])
答
尝试print "Match found"
后if j in data[:]:
只是为了检查,如果条件是见过。我的猜测是没有匹配,因为列表data
是python filemanes(if 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')
它怎么会失败呢?什么(没有)发生? – 2014-10-28 21:01:56
@TimCastelijns: - 没有任何更改。 。没有效果。 。我认为比较两件事情(名单)出了问题。我对**重命名**行不太确定。如果我错了,请纠正我。 – Thuruv 2014-10-28 21:23:08
@TimCastelijns我可以使用字典。 。? 任何方法都可以创建出色的字典。 。? – Thuruv 2014-10-30 00:32:49