Having issue while implementing recursion
The issue has nothing to do with recursion. The traceback shows you that the error didn't occur in a recursive call. It also has nothing to do with the os
module.
The best hint is the path of the nonexistent directory: folder_b/folder_a
. The issue is that you're looping over os.listdir()
, but changing the working directory in the loop, so after cd-ing into folder_b
, it tries to cd into folder_a
, which isn't in folder_b
.
I can think of a few different ways to fix that, but you'd probably be better off not changing the working directory at all. Instead, use os.walk()
to walk the directory branch for you, as well as pathlib
to simplify working with paths. To get you started:
from pathlib import Path
source = Path("/home/smetro/source/")
destination = Path("/home/smetro/Games/destination")
for root, _dirs, files in os.walk(source):
root_rel = Path(root).relative_to(source)
new_root = destination / root_rel
for file in files:
print(new_root / file) # Just for demo