Search code examples
pythonrenameworking-directory

How to run a python script trough a folder with subfolders?


I am ripping dvd's to my plex server, and the way i have done it is like this.

\Storage
    \Movie Name (xxxx)
        Movie.mkv
        Bonus Scene.mkv
    \Movie2 Name (xxxx)
        Movie2.mkv

etc

And what i want to do with my python script is to rename each MKV file to the folder name. But instead of running the script in each folder, how do i run it across the main storage folder and make it enter each subfolder?

My script looks like this (the script requires the movie title to be 1.mkv, i made it like that so it leaves the bonus scenes alone)

import os

folder = "{cwd}\\".format(cwd = os.getcwd())

src = "{folder}".format(folder=folder)

extension = "mkv"


def renamer():
    path = os.path.dirname(src)
    folder = os.path.basename(path)
    os.rename("{directory}\\{file}".format(directory=src, file="1.mkv"),
              "{directory}\\{file}.{extension}".format(directory=src, file=folder, extension = extension))


def listDir():
    for file in os.listdir(src):
        if file.endswith(".{extension}".format(extension = extension)):
            return file


def main():
    renamer()
if __name__ == "__main__":
    main()

Solution

  • you can use:

    for (dirpath, dirnames, filenames) in os.walk(your_initial_directory):
    

    from there you get 3 lists dirpath, dirnames, filenames that are in your_initial_directory