Trying to copy specific files, based on type, from source directory to destination directory. I would like to rename the destination file as it copies over from source to include its parent folder (S:\folder_name - file_name.pdf). Here is what I have so far and it seems to copy the intended files but I can't figure out how to rename the destination file based on source file folder location.
import os
import shutil as sh
root_path = (r"S:\Colocation Information Kory.Williams@charter.com )")
dest_path = (r"C:\Users\P2187119\Documents\MSA_SO Crawl")
for dirpath, dnames, fnames in os.walk(root_path):
for f in fnames:
if f.endswith(".pdf"):
source_file_path = os.path.join(dirpath, f)
dest_file_path = os.path.join(dest_path, f)
sh.copyfile(source_file_path, dest_file_path)
print(f"{f}this is my location from pdf")
elif f.endswith(".doc"):
source_file_path = os.path.join(dirpath, f)
dest_file_path = os.path.join(dest_path, f)
sh.copyfile(source_file_path, dest_file_path)
print(f"{f} this is my location from doc")
elif f.endswith(".docx"):
source_file_path = os.path.join(dirpath, f)
dest_file_path = os.path.join(dest_path, f)
sh.copyfile(source_file_path, dest_file_path)
print(f"{f} this is my location from docx")
Edit:
I can get the following code to print the filenames how I want, but I can't figure out how to introduce copying that file to a new directory and renaming with it's directory path location.
import os
import shutil as sh
from pathlib import Path
for root, dirs, files in os.walk(r'/Users/codychandler/SyncDrive/Colocation Information (Kory.Williams@charter.com )'):
for f in files:
if f.endswith(".pdf"):
print(os.path.abspath(os.path.join(root, f)))