python-3.x 通过替换字符串的一部分来重命名多个文件夹中的子文件夹

vpfxa7rd  于 2023-03-31  发布在  Python
关注(0)|答案(2)|浏览(84)

bounty将在7天后过期。回答此问题可获得+50声望奖励。JodeCharger100希望引起更多人关注此问题。

假设我在许多不同的文件夹(**)中有多个子文件夹。所有的文件夹都在一个名为Project 1的主文件夹中。我想使用substring函数替换文件夹的字符串名称。

import glob
import os 
import pandas as pd

paths = glob.glob("CC:/Users/xxx/College/Project1/**/", recursive=True)

假设子文件夹位于多个文件夹中,并且具有如下命名约定:

fwjekljfwelj-10-fwefw #(the path for this folder is "CC:/Users/xxx/College/Project1/**/wjekljfwelj-10-fwefw/")
kljkgpjrjrel-11-wwref
fwefjkecmuon-12-cfecd
dsfshncrpout-13-lplce
  • 字符前面的字母数字序列是没有意义的。我想用数字20替换虚线前面的字符串。因此,新的子文件夹将是:
2010-fwefw
2011-wwref
2012-cfecd
2013-lplce

我可以使用str.split('-', 1)[-1]为每个子文件夹单独重命名,然后在名称后附加“20”,但我希望自动化该过程。

eh57zj3b

eh57zj3b1#

您可以将os.walktopdown=False一起使用:

import re
import os

top_dir = 'CC:/Users/xxx/College/Project1'

for dirpath, dirnames, filenames in os.walk(base_dir, topdown=False):
    for dirname in dirnames:
        if re.search(r'-\d{2}-', dirname):
            new_dirname = f"20{dirname.split('-', 1)[1]}"
            new_dirpath = os.path.join(dirpath, new_dirname)
            old_dirpath = os.path.join(dirpath, dirname)
            print(f'{old_dirpath} -> {new_dirpath}')
            os.rename(old_dirpath, new_dirpath)

之前:

Project1
└── fldr1
    ├── dsfshncrpout-13-lplce
    ├── fwefjkecmuon-12-cfecd
    ├── fwjekljfwelj-10-fwefw
    └── kljkgpjrjrel-11-wwref

之后:

Project1
└── fldr1
    ├── 2010-fwefw
    ├── 2011-wwref
    ├── 2012-cfecd
    └── 2013-lplce
sqougxex

sqougxex2#

让我们看看这是否适合你:

import os
import glob

# define the base folder
base_folder = "CC:/Users/xxx/College/Project1"

# get all the subfolders
subfolders = glob.glob(os.path.join(base_folder, "**/"), recursive=True)

# iterate over the subfolders
for folder_path in subfolders:
    # get the folder name
    folder_name = os.path.basename(folder_path)
    # split the folder name by the "-" character
    parts = folder_name.split("-")
    # construct the new folder name
    new_folder_name = "20" + parts[-1]
    # get the parent folder path
    parent_folder = os.path.dirname(folder_path)
    # construct the new folder path
    new_folder_path = os.path.join(parent_folder, new_folder_name)
    # rename the folder
    os.rename(folder_path, os.path.join(parent_folder, new_folder_path))

相关问题