Adding foldernames in directory to filename

Viewed 116

I am trying hard and struggling and I hope you guys can help me out maybe:

Hello guys I have a folder with many subfolders and the last subfolder has files in it. I want to write a Python code where I can add the foldernames of all folders in the directory to the end of the filename in brackets.

For example my base directory is C:\Users\cemil.kocyigit\Downloads\Code and it has following structure:

Folder_1
  > SubFolder_1
    > FileName1.abc
    > Filename2.abc
  > SubFolder_2
    > SubSubFolder_1
      > SubFileName1.abc

Folder_2
  > SubFolder11
    > FileName11.abc
    > Filename12.abc
    > ..............

Folder_3
  > Subfolder..........

I want to rename the files into this: FileName1(Subfolder_1)(Folder_1).abc or SubFileName1(SubSubFolder_1)(Subfolder_2)(Folder_1).abc

What I have done until now is:

import os
    
    for root, dirs, files in os.walk("C:\\Users\\cemil.kocyigit\\Downloads\\Code"):
        if not files:
            continue
        prefix = os.path.basename(root)
        for f in files:
            base = os.path.basename(f)
            text = os.path.splitext(base)[0]
            extension = os.path.splitext(base)[1]
            os.rename(os.path.join(root, f), os.path.join(root, "{}({}){}".format(text, prefix, extension)))

With this code I can get the foldername of the folder before but not the foldernames of ALL in that directory?

F.e. I get: FileName1(Subfolder_1).abc

Is there any chance to change the code so it will recursively search for all foldernames in the base directory and at them to the filename?

(Please don´t judge my writing I am mechanical student getting new into coding :))

Thanks in regards!!

1 Answers

You can collect all dirnames beforehand into a string. Then use that string in your final filename.

import os

collected_dirnames = ""
for root, dirs, files in os.walk("C:\\Users\\cemil.kocyigit\\Downloads\\Code=3,56"):
    collected_dirnames = "-".join(dirs)

print(collected_dirnamee) # check if it is 2hat you want

# your code
for root, dirs, files in os.walk("C:\\Users\\cemil.kocyigit\\Downloads\\Code=3,56"):
    if not files:
        continue
    for f in files:
        base = os.path.basename(f)
        text, extension = os.path.splitext(base)
        os.rename(os.path.join(root, f),
                  os.path.join(root, "{}({}){}".format(text, collected_dirnames, extension)))

Is that what you want? It should at least point into the right direction

Related