2017-01-25 56 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 –

相关问题