[Python] How to give a file the same name as the folder that contains it

Discussão em 'Python' iniciado por Stack, Maio 28, 2025.

  1. Stack

    Stack Membro Participativo

    Suppose I have a folder that contains 3 subfolders named A, B, and C. Each subfolder contains one srt file. I'd like to name the file in subfolder A, A.srt ; the file in subfolder B, B.srt ; and the file in subfolder C, C.srt. (Without adding the 'srt' extension, of course).

    How can I do that ? I tried a few things but always get stuck.

    import os

    path = os.getcwd()

    current_folder_name = os.path.basename(path)


    I get stuck when I want to iterate through each subfolder and rename the file it contains after it.

    I tried to modify the following code so it iterates only through the subfolders but I get an error...

    for subdir, dirs, files in os.walk(path):
    for file in files:
    print(os.path.join(subdir, file))


    I am a bit lost. Please help. :)

    Continue reading...

Compartilhe esta Página