[英]Python rename files reading names from csv file
您好,我一直在努力適應這個我需要,但我只是在python newbe,我有多個列和行的csv文件,重要的列1 =文件的舊名稱,以及2 =新名稱文件,因此我需要轉到csv文件中列出的文件所在的目錄,並將其重命名為第2列的新名稱,因為我說我嘗試了很多事情都沒有成功,所以我粘貼了我所做的最后一個代碼你有一個主意:
import os, unicodecsv as csv, sys
IDs = {}
#open and store the csv file
with open('documentos_corpus_ladino.csv','rb') as csvfile:
timeReader = csv.reader(csvfile, delimiter = ',')
# build a dictionary with the associated IDs
for row in timeReader:
IDs[ row[0] ] = row[1]
# #get the list of files
path = 'txt_orig/'
tmpPath = 'txt_tmp/'
for filename in os.listdir('txt_orig/'):
oldname = filename
newname = filename.replace(oldname, csvfile.next().rstrip().split(",")[1])
os.rename(path + filename, tmpPath + newname)
非常感謝。
您應該使用從CSV創建的字典IDs
:
for filename in os.listdir(path):
oldname = filename
newname = IDs[oldname]
os.rename(path + filename, tmpPath + newname)
但是您可能應該使用某種錯誤檢查。.( 編輯如其他答案所指出,最好也使用os.path.join
)也許遵循以下原則:
failed = []
for oldname in os.listdir(path):
try:
old = os.path.join(path, oldname)
new = os.path.join(tmpPath, IDs[oldname])
os.rename(old, new)
except KeyError, OSError:
failed.append(oldname)
print failed
這將重命名每個匹配的文件,並報告任何嘗試重命名的錯誤。 它不會嘗試移動不存在的文件。
import os, unicodecsv as csv
# open and store the csv file
IDs = {}
with open('documentos_corpus_ladino.csv','rb') as csvfile:
timeReader = csv.reader(csvfile, delimiter = ',')
# build dictionary with associated IDs
for row in timeReader:
IDs[row[0]] = row[1]
# move files
path = 'txt_orig/'
tmpPath = 'txt_tmp/'
for oldname in os.listdir(path):
# ignore files in path which aren't in the csv file
if oldname in IDs:
try:
os.rename(os.path.join(path, oldname), os.path.join(tmpPath, IDs[oldname]))
except:
print 'File ' + oldname + ' could not be renamed to ' + IDs[oldname] + '!'
您正在文件上進行迭代,並將舊名稱和新名稱存儲在IDs
但不使用它,而只是嘗試從文件中進一步讀取(這顯然會失敗,因為此時您已經讀取了整個文件)。 IOW,您應該使用IDs
字典來獲取新名稱(使用舊名稱作為鍵),即:
path = 'txt_orig' # no trailing slash required
tmpPath = 'txt_tmp' # idem
for filename in os.listdir(path):
try:
newname = IDs[filename]
except KeyError:
print "no new name for '%s'" % filename
continue
else:
os.rename(os.path.join(path, filename), os.path.join(tmpPath, newname))
現在有一個更簡單的解決方案:在對csv文件進行迭代時,只需重命名文件即可:
path = 'txt_orig'
tmp_path = 'txt_tmp'
with open('documentos_corpus_ladino.csv','rb') as csvfile:
reader = csv.reader(csvfile, delimiter = ',')
for row in reader:
oldname = os.path.join(path, row[0])
if os.path.exists(oldname):
newname = os.path.join(tmp_path, row[1])
os.rename(oldname, newname)
print >> sys.stderr, "renamed '%s' to '%s'" % (oldname, newname)
else:
print >> sys.stderr, "file '%s' not found" % oldname
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.