Problem while recursively and selectively copying a folder in python scipt

51 Views Asked by At

I want to make a python script that recursively copies from src to dest and and I also want to make some rules like it shoudn't copy .py files or .log files. I have to tried ignore_pattern but using shutil.copyfile . All the files are getting copied to the same destination directories. No sub directories are created. Please help me with that.

CODE :

import os
import re
from datetime import datetime
from distutils.file_util import copy_file

file1 = open("E:\Test\upgrade.log","a")  
log=""""""
src="E:\Test\src"
dest="E:\Test\dest"
src_files =os.listdir(src)
filtered_files = [i for i in src_files if not re.findall(".bmp",i)]
for file_name in filtered_files:
    full_file_name = os.path.join(src, file_name)
    log = log + datetime.now().strftime("%d/%m/%Y %H:%M:%S")+" "+ file_name
    if os.path.isfile(full_file_name):
        log = log + " Copied Successfully to " + dest
        copy_file(full_file_name,dest)
    log = log + "\n"    
file1.write(log)
file1.close()
print(log)
1

There are 1 best solutions below

1
On

Maybe this can help you:

import os
import shutil

def cpy(src_folder, dest_folder)
   for root, dirs, files in os.walk(src_folder):  
      for file in files:
         file_type = os.path.splitext(file)[1]
         if str(file_type) == "py" or if str(file_type) == "log":
             continue
         else:
             path_file = os.path.join(root,file)
             shutil.copy2(path_file, dest_folder)