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

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

最佳答案

这是你想要的吗?

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 exists in the 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 will 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脚本递归重命名文件夹和子文件夹中的所有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41861238/

相关文章:

python - 如何在 Django 中过滤具有日期范围的查询

python - 通过 Python 从 .idx3-ubyte 文件或 GZIP 中提取图像

python - 如何在 KivyMD (Python) 中组合抽屉导航和多个屏幕?

python - Content-Type header 是否适用于 PUT 或 POST 以外的任何 HTTP 动词?

linux - 了解 NASM 程序集中的递归阶乘函数

c - 为什么我的变量在我的 C 程序中递归调用时改变值?

java - 使用递归计算字符串中 hi 的出现次数

c - 递归函数调用中的段错误(核心转储)

c# - N皇后算法。情节扭曲 : The Queen is a Knight too

python - Pandas :如何对列值拆分的子数据框应用操作