2014-10-28 74 views
0

文件名我有:散裝搜索/替換使用python

  1. Excel文件爲A1:B2。
  2. 一個包含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]) 
+1

它怎麼會失敗呢?什麼(沒有)發生? – 2014-10-28 21:01:56

+0

@TimCastelijns: - 沒有任何更改。 。沒有效果。 。我認爲比較兩件事情(名單)出了問題。我對**重命名**行不太確定。如果我錯了,請糾正我。 – Thuruv 2014-10-28 21:23:08

+0

@TimCastelijns我可以使用字典。 。? 任何方法都可以創建出色的字典。 。? – Thuruv 2014-10-30 00:32:49

回答

0

嘗試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') 
+0

空白列表返回。 。對不起,'old'應該被替換爲'excel'。 。編輯。 如果文件擴展名是'.py',則附加相應的文件名。它應該被替換爲data.append(glob.glob('*。py'))'。 。對。 。? 請檢查它。 。 – Thuruv 2014-10-29 17:43:38

+0

檢查我的編輯,它可能會幫助 – Ruben 2014-10-31 12:55:59

+0

很高興它的工作。改變了我的需求。 – Thuruv 2014-10-31 17:25:53