使用列表中保存的值从子目录名称中删除子字符串

removing substrings from subdirectory names using values held in list

我有一个包含很多子目录的父目录。我想创建一个循环遍历所有子目录并删除我在列表变量中指定的任何关键字的脚本。

我不太确定如何实现。

目前我有这个:

import os
directory = next(os.walk('.'))[1]


stringstoremove = ['string1','string2','string3','string4','string5']


for folders in directory:
    os.rename

也许这种类型的逻辑会检查字符串是否存在于子目录名称中:

if any(words in inputstring for words in stringstoremove):
    print ("TRUE")
else:
    print ("FALSE")

尽量去解构任务,但我现在在兜圈子

谢谢大家

如果您想重命名那些在您的 stringstoremove 列表中匹配的子目录,那么以下脚本会有所帮助。

import os
import re

path = "./" # parent directory path
sub_dirs = os.listdir(path)
stringstoremove = ['string1','string2','string3','string4','string5']
for directory_name in sub_dirs:
    if os.path.isdir(path + directory):
        for string in stringstoremove:
            if string in directory_name:
                try:
                    new_name = re.sub(string, "", directory_name)
                    os.rename(path + directory, path + new_name) # rename this directory
                except Exception as e:
                    print (e)

从您现有的代码开始:

import os
directory = next(os.walk('.'))[1]

stringstoremove = ['string1','string2','string3','string4','string5']

for folder in directory :
    new_folder = folder
    for r in stringstoremove :
        new_folder = new_folder.replace( r, '')

    if folder != new_folder :  # don't rename if it's the same
        os.rename( folder, new_folder )