Python脚本递归重命名文件夹和子文件夹中的所有文件 [英] Python script recursively rename all files in folder and subfolders

查看:69
本文介绍了Python脚本递归重命名文件夹和子文件夹中的所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多不同的文件需要重命名为其他文件.我已经做到了这一点,但我想拥有它,以便我可以有许多项目要替换及其相应的替换项,而不是键入每个项目,然后运行代码然后再次重新键入.

Hi I have a number of different files that need to be renamed to something else. I got this far but I want to have it so that I can have many items to replace and their corresponding replacements rather than type each one out, run the code then retype it again.

更新*此外,我需要重命名以仅更改文件的一部分而不是整个文件,因此如果有Cat5e_1mBend1bottom50m2mBend2top-Aqeoiu31",它只会将其更改为'Cat5e50m1mBED_50m2mBE2U-Aqeoiu31"

UPDATE* Also I need the rename to only change part of the file not the whole thing so if there was a "Cat5e_1mBend1bottom50m2mBend2top-Aqeoiu31" it would just change it to "'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))

推荐答案

这是你想要的吗?

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

检查这是否是您想要的!!!

Check if this is wath you want!!!

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)

这篇关于Python脚本递归重命名文件夹和子文件夹中的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆