2017-01-25 53 views
2

嗨我有一些不同的文件需要重新命名爲其他內容。我得到了這麼多,但我想擁有它,以便我可以有許多項目來替換和相應的替換,而不是輸入每個項目,運行代碼,然後再次輸入。Python腳本遞歸地重命名文件夾和子文件夾中的所有文件

UPDATE *此外,我需要重命名只更改文件的一部分,而不是整個事情,所以如果有一個「Cat5e_1mBend1bottom50m2mBend2top-Aqeoiu31」它只是將其更改爲「'Cat5e50m1mBED_50m2mBE2U-Aqeoiu31"

import os, glob 

#searches for roots, directory and files 
for root,dirs, files in os.walk(r"H:\My Documents\CrossTalk\\"): 
    for f in files: 
     if f == "Cat5e_1mBend1bottom50m2mBend2top":#string you want to rename 
      try: 
      os.rename('Cat5e_1mBend1bottom50m2mBend2top', 'Cat5e50m1mBED_50m2mBE2U')) 
      except FileNotFoundError, e: 
      print(str(e)) 
+0

什麼是您將製作的文件名稱中的常見替代品? –

回答

3

這是你想要的嗎?

import os, glob 
#searches for roots, directory and files 
#Path 
p=r"C:\\Users\\joao.limberger\\Documents\\Nova Pasta" 
# rename arquivo1.txt to arquivo33.txt and arquivo2.txt to arquivo44.txt 
renames={"arquivo1.txt":"arquivo33.txt","arquivo2.txt":"arquivo44.txt"} 
for root,dirs,files in os.walk(p): 
    for f in files: 
     if f in renames.keys():#string you want to rename 
     try: 
      os.rename(os.path.join(root , f), os.path.join(root , renames[f])) 
      print("Renaming ",f,"to",renames[f]) 
     except FileNotFoundError as e: 
      print(str(e)) 

檢查這是否是你想要的!

import os, glob 
#searches for roots, directory and files 
#Python 2.7 
#Path 
p=r"C:\\Users\\joao.limberger\\Documents\\Nova Pasta" 
# if the substring in the key exist in filename, replace the substring 
# from the value of the key 
# if the key is "o1" and the value is "oPrinc1" and the filename is 
# arquivo1.txt ... The filename whil be renamed to "arquivoPrinc1.txt" 
renames={"o1":"oPrinc1","oldSubs":"newSubs"} 
for root,dirs,files in os.walk(p): 
    for f in files: 
     for r in renames: 
      if r in f: 
       newFile = f.replace(r,renames[r],1) 
       try: 
        os.rename(os.path.join(root , f), os.path.join(root , newFile)) 
        print "Renaming ",f,"to",newFile 
       except FileNotFoundError , e: 
        print str(e) 
+0

'if if in renames.keys()'=>'if f在重命名',更pythonic,更快。 –

+0

沒有,沒有工作,它重命名所有的文件。我只想要重命名文件的一部分。對不起,如果我混淆你,請看看上面的更新 – VisualExstasy

+0

謝謝@ Jean-FrançoisFabre我是Python編程新手!!!! –

2

你需要的第一件事就是爲替換,然後在你的代碼的變化較小的dictionary

import os, glob 

name_map = { 
    "Cat5e_1mBend1bottom50m2mBend2top": 'Cat5e50m1mBED_50m2mBE2U' 
} 

#searches for roots, directory and files 
for root,dirs,files in os.walk(r"H:\My Documents\CrossTalk"): 
    for f in files: 
     if f in name_map: 
      try: 
      os.rename(os.path.join(root, f), os.path.join(root, name_map[f])) 
      except FileNotFoundError, e: 
      #except FileNotFoundError as e: # python 3 
      print(str(e)) 

在name_map中,key(字符串的「:」左)是名fil e在您的文件系統中,並且value(「:」右側的字符串)是您要使用的名稱。

+1

這將無法正常工作:您必須加入'root'目錄或'rename'將會失敗。 –

+0

@ Jean-FrançoisFabre嘿,你幫我上了我的最後一個劇本,有什麼建議嗎? – VisualExstasy

+0

是的,謝謝@ Jean-FrançoisFabre –

相關問題