I've written the following renaming tool in Python. It was unintentionally moving all my files to a single directory until I added the os.chdir in my for loop, which then made it work better and keep each renamed file inside its correct folder. But I don't really understand the logic behind why this script, without the os.chdir, was moving all my files to a single directory, can somebody help me understand? Thank you.
import pathlib
from pathlib import Path
import os
folderDir = Path(input("Please enter the parent directory: \n"))
folderList = [folder for folder in folderDir.iterdir() if folder.is_dir()]
for f in folderList:
fileList = [e for e in f.iterdir() if e.is_file()]
os.chdir(f)
count = 1
for i in fileList:
folderName = os.path.basename(os.path.dirname(i))
i.rename(folderName + "_" + str(count).zfill(3) + pathlib.Path(i).suffix)
count += 1