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. Instead of some of these examples:
CarItems/Chevrolet/Chevelle/2011/parts.txt
CarItems/Chevrolet/Chevelle/1982/parts.txt
CarItems/Chevrolet/Volt/1994/parts.txt
it should look like this:
CarItemsCopy/Chevrolet/Chevelle/parts-2011.txt
CarItems/Chevrolet/Chevelle/parts-1982.txt
CarItems/Chevrolet/Volt/parts-1994.txt
Do this using Python (you can't create the copy by manually rearranging things). You may use the os module's walk generator. Hint: You might find the os.path module's split function to be helpful. You don't have to use it though.
This is the code I have got so far:
def create_dir(dir_path):
""" Creates a new directory.
This function is used to create a new directory.
Positional Input Parameter:
directory: Car
Keyword Input Parameters:
None
"""
if not os.path.exists(dir_path):
former_path, sub_dir = os.path.split(dir_path)
if os.path.exists(former_path) or former_path == "":
os.mkdir(dir_path)
else:
create_dir(former_path)
os.mkdir(dir_path)
for dirpath, dirname, filename in os.walk("CarItems"):
if len(filename) > 0:
sub_path, year = os.path.split(dirpath)
for i in filename:
name, suffix = os.path.splitext(i)
new_file = name + "-" + year + suffix
new_path = sub_path.replace("CarItems", "CarItemsCopy")
create_dir(new_path)
file_path = os.path.join(dirpath, i)
new_file_path = os.path.join(new_path, new_file)
shutil.copy2(file_path, new_file_path)
FileNotFoundError: [Errno 2] No such file or directory: '' this is the error I'm getting on a Mac, on a windows it works perfectly. My question, why is that, and what adjustment would need to be made for it to work on a mac? Thanks!