【问题标题】:Python - concatenate root directory name with all sub-folder namesPython - 将根目录名称与所有子文件夹名称连接起来
【发布时间】:2020-10-23 11:35:21
【问题描述】:

我有一个根文件夹“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)

【问题讨论】:

    标签: python rename


    【解决方案1】:
    import os
    import shutil
    
    test_directory = "./topfolder"
    for child in os.listdir(test_directory):
        test_path = os.path.join(test_directory, child)
        if os.path.isdir(test_path):
          shutil.move(test_path, os.path.join(test_directory, f"{test_directory}_{child}"))
    

    如果您想保留原始文件夹,可以将move 替换为以下内容

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

    【讨论】:

      【解决方案2】:

      试试os.rename:

      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)
      

      【讨论】:

        【解决方案3】:

        要更改目录名称,请查看change folder names。它正在使用 os.rename

        对于父名,可以使用split。

        path = os.path.dirname(CURRENT_DIR)
        path.split('/')[-1]
        

        CURRENT_DIR 是您当前的工作目录,假设是 child

        现在你有一个孩子和父母的名字。您可以将它们连接起来并从上面的参考中重命名它们。

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

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

        这里你的分隔符是'-'并且你有孩子在循环中

        【讨论】:

          猜你喜欢
          • 2013-12-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多