Currently, I am working on a project in which am synchronizing two folders. My folders in the following example names ad Folder_1 as source and Folder_2 as destination I want to do the following things.
I have done half the part of point one in which I am able to copy the files from Folder_1 to Folder_2. Send part where I could be able to copy files from Folder_2 to folder_1 is still remaining.
Following is my code
import os, shutil
path = 'C:/Users/saqibshakeel035/Desktop/Folder_1/'
copyto = 'C:/Users/saqibshakeel035/Desktop/Folder_2/'
files =os.listdir(path)
files.sort()
for f in files:
src = path+f
dst = copyto+f
try:
if os.stat(src).st_mtime < os.stat(dst).st_mtime:
continue
except OSError:
pass
shutil.copy(src,dst)#this is the case when our file in destination doesn't exist
=
print('Files copied from'+ path +'to' + copyto+ '!')
What can I amend or do so that I can synchronize both folders completely? Thanks in advance :)
(Not the same approach as yours but gets the work done as expected from your query)
Simple code using dirsync
:
from dirsync import sync
source_path = '/Give/Source/Folder/Here'
target_path = '/Give/Target/Folder/Here'
sync(source_path, target_path, 'sync') #for syncing one way
sync(target_path, source_path, 'sync') #for syncing the opposite way
See documentation here for more options: dirsync - PyPI
You can, of course, add exception handling manually if you want.