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
You do need the walk to get to all the filenames, though you can directly figure out the new filenames.
The psuedocode:
# Make a list of filenames with os.walk
# For each filename in that list:
# If the filename matches a regex of ending with four digits, slash, name
# make the new filename
# use os.rename to move the original file to the new file.
You need to make a separate list rather than just for name in os.walk...
because we will be changing the contents as we go.
Creating a regex with Regex101, we get a solution. You may want to try it yourself before looking at this:
import os
import re
pattern = r'(.*)(\\|/)(\d\d\d\d)(\\|/)(\w+)(\.txt)'
# Note r'..' means raw, or take backslashes literally so the regex is correct.
filenames = [ os.path.join(dir_, name)
for (dir_, _, names) in os.walk('.')
for name in names ]
# Note 'dir_' because dir is reserved word
# Note '_' as pythonic way of saying 'an ignored value'
# Note for loops are in same order in list comprehension as they would be in code
for filename in filenames:
m = re.match(pattern, filename)
if m:
front, sep1, year, sep2, name, ext = m.groups()
new_filename = f'{front}{sep1}{name}-{year}{ext}'
# print(f'rename {filename} to {new_filename}')
os.rename(filename, new_filename)
Keep Hacking! Keep notes.
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.