codychandler
codychandler

Reputation: 43

Copying files from source to destination and append destination file name

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 [email protected] )")
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 ([email protected] )'):
for f in files:
    if f.endswith(".pdf"):
        print(os.path.abspath(os.path.join(root, f)))

Upvotes: 3

Views: 382

Answers (1)

blunova
blunova

Reputation: 2532

Try this:

import os
import shutil as sh
from pathlib import Path


root_path = Path("S:\\Colocation Information ([email protected] )")
dest_path = Path("C:\\Users\\P2187119\\Documents\\MSA_SO Crawl")


for root, _, fnames in os.walk(root_path):
    for f in fnames:
        source_file_path = Path(root, f)
        ext = source_file_path.suffix
        dest_file_path = Path(
            dest_path, f"{source_file_path.stem}_{root_path.stem}{source_file_path.suffix}"
        )
        sh.copyfile(source_file_path, dest_file_path)

Avoid to hardcode paths in your code, it's a very bad habit, but instead use a configuration file for storing them, like json or yaml files. Moreover, pay attention to how to use backslashes when typing paths in your scripts; I have added a double backslash or you could use one single forward slash.

Then, you had to much duplicate lines in your code.

When your are dealing with paths, I suggest you to use the pathlib library, it will make the handling of paths a lot easier.

EDIT

In case you want your copied file to have the full path of your root folder in their name and not just the name of the root folder, you can modify the code like this (it is necessary to remove the colon and backslash chars):

import os
import shutil as sh
from pathlib import Path


root_path = Path("C:\\Users\\Blunova\\Desktop\\scripts\\python\\so\\Colocation Information ([email protected] )\\")
dest_path = Path("C:\\Users\\Blunova\\Desktop\\scripts\\python\\so\\P2187119\\Documents\\MSA_SO Crawl")


backslash_char = "\\"
colon_char = ":"

for root, _, fnames in os.walk(root_path):
    for f in fnames:
        source_file_path = Path(root, f)
        ext = source_file_path.suffix
        dest_file_path = Path(
            dest_path,
            f"{source_file_path.stem}"
            f"_{str(root_path.resolve()).replace(backslash_char, '_').replace(colon_char, '')}"
            f"{source_file_path.suffix}"
        )
        sh.copyfile(source_file_path, dest_file_path)

For instance, let's imagine that you have a file called pdf_file.pdf stored in your root_path (with nested folders) which is:

C:\\Users\Blunova\Desktop\scripts\python\so\Colocation Information ([email protected] )

Then, if your run the code above you will get the following name for the copied file (copied from the root path within the destination folder):

pdf_file_C_Users_Blunova_Desktop_scripts_python_so_Colocation Information ([email protected] ).pdf

Upvotes: 3

Related Questions