Create a copy of the CarItems tree called CarItemsCopy where all files, instead of being in directories named after years, rather have the year as part of the filename, and the
In the what it should look like section I think you made a mistake. Only one directory will exist under CarItemsCopy
, the other will be renamed where they're located.
Task:
Create a copy of the CarItems
tree called CarItemsCopy
where all files, instead of being in directories named after years, rather have the year as part of the filename, and the year directories are entirely absent.
The path
, shutil
, and os
modules should simplify the task:
from pathlib import Path
import os
from shutil import copy2
# Place this script in the CarItems folder.
# The full path to our CarItems folder.
script_dir = Path(os.path.dirname(os.path.abspath(__file__)))
source_dir = script_dir.joinpath("Caritems")
for folder in source_dir.iterdir():
for subfolder in folder.iterdir():
subfolder_with_parts = subfolder.joinpath("parts.txt")
if subfolder_with_parts.exists(): # Only continue if parts.txt exists.
ext = subfolder_with_parts.suffix # In this case .txt
parts = Path(f"CarItemsCopy//{folder.stem}//parts-{subfolder.stem}{ext}")
car_copy = script_dir.joinpath(parts)
car_copy.parent.mkdir(parents=True, exist_ok=True)
copy2(subfolder_with_parts, car_copy) # Will attempt to copy the metadata.