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

时间:2019-08-28 00:08:13

标签: python subdirectory file-rename

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

目录的当前设置:

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

1 个答案:

答案 0 :(得分:0)

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

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