Prottoy
Prottoy

Reputation: 131

Copy files from a folder and Paste to another directory sub-folders in python

I am a newbie in python. I searched and tried but could not be figured it out, can someone please help me?

I want to copy files from a folder and want to paste an inside folder of all sub-folders (not parent folder) only all subfolders

Here I have done only copied files and paste them to the destination directory, not on subfolders.

import shutil
import os, sys
    
exepath = sys.argv[0]

zip_directory = os.path.dirname(os.path.abspath(exepath))+"\\Files\\"

credit_folder = os.path.dirname(os.path.abspath(exepath))+"\\Pictures\\"

os.chdir(credit_folder)
os.chdir(zip_directory)

SourceCredits = credit_folder
TargetFolder = zip_directory

files = os.listdir(SourceCredits)

for file in files:
     shutil.copy(os.path.join(SourceCredits,file), TargetFolder)

Left side folder is Files folder and the right side is credit folder

Upvotes: 0

Views: 1316

Answers (1)

Prottoy
Prottoy

Reputation: 131

I was stuck on pasting credits files to all subdirectories, so first, I checked all the dir via listdir, and implements for loop for both dirs. so I had only files inside credits, it made three different copies (based on folders of target dir (i had 3 sub-folders) )

in the end, I implement the shutil.copy2 to the source to target for pasting my copied files.

import shutil
import os, sys

exepath = sys.argv[0]

directory = os.path.dirname(os.path.abspath(exepath))+"\\Files\\"

credit_folder = os.path.dirname(os.path.abspath(exepath))+"\\Credits\\" 

os.chdir(credit_folder)
os.chdir(directory)

Source = credit_folder
Target = directory

files = os.listdir(Source)
folders = os.listdir(Target)

for file in files:
    SourceCredits = os.path.join(Source,file)

    for folder in folders:
        TargetFolder = os.path.join(Target,folder)

        shutil.copy2(SourceCredits, TargetFolder)

 print(" \n ===> Credits Copy & Paste Sucessfully <=== \n ")

Upvotes: 1

Related Questions