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

标签 python rename

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

最佳答案

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

关于Python-将根目录名称与所有子文件夹名称连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62703630/

相关文章:

python - 如何在 python 中用数字重命名多个列?

Python 文件创建日期和重命名 - 请求批评

python - XlsxWriter 中的条形着色以正/负值为条件

python - 是否可以在 heroku 上运行 scrapy?

python - 使用 python-oauth2 签署请求

batch-file - 如何复制和重命名

Python 3 打印不带括号

python - 无法在pycharm中使用tensorflow

Java:DOM 如何从名称列表中重命名节点名称

linux - 用空格重命名文件