[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).

    I tried this:

    import os

    path = os.getcwd()

    for (dirname, dirs, files) in os.walk(path):
    for file in files:
    if file.endswith('.srt'):
    folder_name = os.path.basename(dirname)
    os.rename(file, folder_name)


    but it says the file is not found... although I see the file name in my console when I do print(file).

    I am a bit lost. Please help. :)

    Continue reading...

Compartilhe esta Página