Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-将根目录名与所有子文件夹名连接起来_Python_Rename - Fatal编程技术网

Python-将根目录名与所有子文件夹名连接起来

Python-将根目录名与所有子文件夹名连接起来,python,rename,Python,Rename,我有一个根文件夹“topfolder”。在该文件夹中,我有多个子文件夹“a”、“b”、“c”。 我想重命名这些子文件夹,以便它们与根文件夹连接,从而使它们成为“topfolder_a”、“topfolder_b”等等。 用Python做这件事相对容易吗? 我想我的代码就快到了,但我不能得到最后一部分 test_directory = "./topfolder" for child in os.listdir(test_directory): test_path = o

我有一个根文件夹“topfolder”。在该文件夹中,我有多个子文件夹“a”、“b”、“c”。 我想重命名这些子文件夹,以便它们与根文件夹连接,从而使它们成为“topfolder_a”、“topfolder_b”等等。 用Python做这件事相对容易吗? 我想我的代码就快到了,但我不能得到最后一部分

test_directory = "./topfolder"
for child in os.listdir(test_directory):
    test_path = os.path.join(test_directory, child)
    if os.path.isdir(test_path):
        print(test_path)
如果您想保留原始forder,可以将
move
替换为以下内容

shutil.copytree(test_path, os.path.join(test_directory, f"{test_directory}_{child}"))

尝试操作系统。重命名:

import os

test_directory = "./topfolder"
for child in os.listdir(test_directory):
    test_path = os.path.join(test_directory, child)
    rename_path = os.path.join(test_directory, test_directory + "_" + child)
    if os.path.isdir(test_path):
        print(test_path, rename_path)
        os.rename(test_path, rename_path)

要更改目录名,请选中此项。它正在使用os.rename

对于父名称,可以使用“拆分”

path = os.path.dirname(CURRENT_DIR)
path.split('/')[-1]
CURRENT_DIR是您当前的工作DIR,在您的情况下,它是
子项

现在你有了孩子和父母的名字。您可以从上面的引用中连接它们并重命名它们

这是一个很长的解决方案。但它解释了它将如何工作。 但是重命名采用完整路径,因此您可以直接传递要重命名的路径

os.rename(CURRENT_DIR, test_directory + SEPERATOR + child)
在这里,你的分隔符是“-”,循环中有子循环

os.rename(CURRENT_DIR, test_directory + SEPERATOR + child)