import os
import re
import shutil

# Traverse each file
sourcedir = "C:\\Users\\ShantanuGupta\\Desktop\\OzSc1\\InputFolder"
# Search for folder in Location 1
destinationdir1 = r"C:\Users\ShantanuGupta\Desktop\OzSc1\OutputFolder1"
# Search for folder in Location 2
destinationdir2 = "C:\\Users\\ShantanuGupta\\Desktop\\OzSc1\\OutputFolder2"
# Put files in folder "Folder Not Found"
destinationdir3 = "C:\\Users\\ShantanuGupta\\Desktop\\OzSc1\\OutputFolder3\\FoldersThatCouldNotBeFound"

regex = re.compile(r'^A\d{5}', re.IGNORECASE) #Checking only first six characters

count = 0
for files in os.listdir(sourcedir):  # looping over different files
    if regex.match(files):
        print(files)

    found = False

    # Search for a folder in Location 1
    for folderName in os.listdir(destinationdir1):
        if regex.match(folderName):
            print(folderName)
            # Copy the files from the input folder to output folder
            shutil.copy(sourcedir+'/'+files, destinationdir1+'//'+folderName)
            found = True
            break

    if not found:
        print('folder not found in Location1')
        count = 1

    # Search for a folder in Location 2
    for folderName in os.listdir(destinationdir2):
        if regex.match(folderName):
            #print(folderName)
            # Copy the files from the input folder to output folder
            shutil.copy(sourcedir+'/'+files, destinationdir1+'/'+folderName+'/'+files)
            found =  True
            break

    if not found:
        print('folder not found in Location2')
        count = 2

    # Folder Not Found
    if not found:
        print('copyingfilesinfoldernotfound')
        # Copy the files from the input folder to folder not found
        shutil.copy(sourcedir+'/'+files, destinationdir3+'/'+files)