2

I have a root folder "topfolder". Inside that folder, I have multiple subfolders, "a", "b", "c". I want to rename these subfolders so that they are concatenated with the root folder, such that they become "topfolder_a", "topfolder_b" and so on. Is this relatively easy to do with Python? I think I am almost there with this code but I can't get the last part.

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)
warsong
  • 1,008
  • 2
  • 12
  • 21

3 Answers3

1

Try 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)
warsong
  • 1,008
  • 2
  • 12
  • 21
Hao Li
  • 1,593
  • 15
  • 27
1

For changing dir name check this change folder names. It's using os.rename

For the parent name, you can use split.

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

CURRENT_DIR is your current working dir in your case it's child is suppose.

Now you have a child and parent name both. You can figure concatenate them and rename them from the reference above.

Well, that's a long solution. but it explains how it'll work. but rename takes full path so you can directly pass the path to rename

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

here your SEPERATOR is '-' and you have the child in the loop

7u5h4r
  • 459
  • 3
  • 10
0
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}"))

In case you want to retain the orginal forder you can replace move with below

shutil.copytree(test_path, os.path.join(test_directory, f"{test_directory}_{child}"))
mujjiga
  • 16,186
  • 2
  • 33
  • 51