如何通过复制子文件夹中的文件名来重命名子文件夹?

How to rename subfolders by copying the name of the file in the subfolder?

我正在尝试根据文件夹中的文件名重命名子文件夹。我希望文件夹名称和文件名称相同。目前我有一个脚本循环遍历所有子文件夹并将文件重命名为正确的名称。现在我需要使用那个 "correct name" 并用相同的名称重命名该文件所在的子文件夹。

当前目录设置:

Folder A(Parent folder)

    Folder sample1(Sub folder)
       1. sample.pdf
       2. correct_name1.xml

    Folder B2(Sub folder)
       1. sample.pdf
       2. correct_name2.xml

    Folder B3(Sub folder)
       1. sample.pdf
       2. correct_name3.xml

预期输出:

 correct_name1 B1(Sub folder)
       1. correct_name1.pdf
       2. correct_name1.xml

    correct_name2 B2(Sub folder)
       1. correct_name2.pdf
       2. correct_name2.xml

    correct_name3 B3(Sub folder)
       1. correct_name3.pdf
       2. correct_name3.xml

此外,如果有人可以帮助重命名 pdf 文件,我们将不胜感激。 pdf 文件的名称与 xml 完全相同。

我尝试在 if 语句中添加它,但它没有重命名子文件夹。

for dir in dirs:
     sub_folder = os.path.join(path,curr_fld,dir)
     print(sub_folder)
     os.rename(sub_folder,new_name2)

我的代码:

def rename(path)
for root, dirs, files in os.walk(path):
        for file in files:
            curr_fld = os.path.basename(root)
            old_name = os.path.join(path,curr_fld,file)

            if file.endswith(".xml"): 
                file_name, file_ext = os.path.splitext(file)
                print(file_name)

                new_name = "{}-{}-{}-{}{}".format(cfr, year, title, item_id, file_ext) # this is what i had done originally to get the correct file name
                new_name2 = os.path.join(path,curr_fld,new_name) #my correct name

                try:
                    os.rename(old_name,new_name2) 
                except WindowsError:
                     print("Didn't work!")

如果 files 列表包含 .xml 文件,您应该使用 root 作为要重命名的目录:

def rename(path):
    for root, _, files in os.walk(path):
        try:
            new_name, _ = next(os.path.splitext(file) for file in files if file.endswith('.xml'))
        except StopIteration:
            continue
        os.rename(root, os.path.join(os.path.dirname(root), new_name))