0

I am trying to iterate through a directory, do something to each of the files and then save a new file with a different name similar to the question here, but I am looking for a solution using pathlib. I am just not sure how to add the desired ending to the end of the file name

movie_dir = pathlib.Path("/movies")
save_dir = pathlib.Path("/corrected_movies")


for dir in movie_dir.iterdir():
    for movie_path in dir.iterdir():
        save_path = save_dir / movie_path # want to add _corrected.avi to end of file name

keenan
  • 462
  • 3
  • 12
  • 1
    so `/movies` has nested subdirectories? be careful here, because `movie_path` will be an absolute path and `save_dir / movie_path` will just resolve again to `movie_path`. – wim Feb 21 '23 at 23:14
  • hmm okay, then I guess I also need to extract the file name from the directory and not the absolute path. There are too many pending edits right now but will update the question shortly – keenan Feb 21 '23 at 23:16

2 Answers2

1

So, assuming your movie_path paths have the correct extension already, you can do something like:

save_path = save_dir / move_path.with_stem(movie_path.stem + "_corrected")

If they don't have the same extension, then you can add:

save_path = save_dir / move_path.with_stem(movie_path.stem + "_corrected").with_suffix(".avi")

Also, as mentioned in the comments, be careful that movie_path is going to be an absolute path! Do a dry run to see. If that is the case, and you could simply extract the .name, so:

save_path = (
    save_dir / move_path.with_stem(movie_path.stem + "_corrected").with_suffix(".avi").name
)

Although, given your situation and not having to keep the original extension, I think this can just be simplified to:

save_path = save_dir / (movie_path.stem + "_corrected.avi")
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
0

Similar question here : Adding another suffix to a path that already has a suffix with pathlib

If you use pathlib3x : append_suffix function

or you can do like that :

save_path = (save_dir / pathlib.Path(str(movie_path) + "_corrected.avi"))

you can put this little code in a function to simulate append_suffix, like for example :

def append_suffix(path):
    return pathlib.Path(str(path) + "_corrected.avi")

save_path = save_dir / append_suffix(movie_path)

If your movies have already a .avi extension, just add a slice operation (or something similar) :

def append_suffix(path):
    return pathlib.Path(str(path)[:-4] + "_corrected.avi")
ooO___Ooo
  • 1
  • 1