Python脚本递归地重命名文件夹和子文件夹中的所有文件

时间:2017-01-25 20:37:41

标签: python recursion

您好我有许多不同的文件需要重命名为其他内容。我得到了这个,但我想拥有它,以便我可以有许多项目来替换和相应的替换而不是输入每一个,运行代码然后再次重新键入它。

更新*另外我需要重命名只改变文件的一部分而不是整个文件,所以如果有一个" 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))

2 个答案:

答案 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)

答案 1 :(得分: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(“:”左侧的字符串)是文件系统中文件的名称,以及value(右侧的字符串) “:”)是您要使用的名称。