Reputation: 53
I need a python script that will watch directory changes every 5 minutes and copy only added files. Do not copy existing files from the source directory. Copy files after the program is started. My program copies files when I delete files on the destination. My python version is 3.6.32
Hear are my code:
import os, time, subprocess, sys, shutil
t = 5
os.chdir('C:\\')
print(os.path.isdir("C:\\Users\\Desktop\\source\\"))
path_to_watch = ("C:\\Users\\Desktop\\source\\")
before = dict ([(f, None) for f in os.listdir (path_to_watch)])
dir_src = ("C:\\Users\\Desktop\\source\\")
dir_dst = ("D:\\dest\\")
while True:
for filename in os.listdir(dir_src):
if filename.endswith('.txt'):
shutil.copy(os.path.join(dir_src + filename), os.path.join(dir_dst + filename))
time.sleep(t)
Upvotes: 0
Views: 440
Reputation: 3208
Try this code,I modified your code a little. It will copy files from source directory to destination. Once it copied one file it will not copy the file even if it is deleted in source or destination. It will copy only newly added files.
import os, time, shutil
path_to_watch = "x/y/z/source"
destination = "a/b/c/destination"
source_files = set(os.listdir(path_to_watch)) # all the file names in the source directory is stored here.
new_files = set() # this is for new files, new files will be updated in source_files too.
while True:
for name in new_files:
if name.endswith('.txt'):
shutil.copy(os.path.join(path_to_watch,name), destination) # copy files presnt in new_files
time.sleep(5*60)
new_files = set(os.listdir(path_to_watch)) # get current files present in source_directory
new_files = new_files - source_files # check if there are actually new files
if new_files: # if there is a new file
source_files = source_files.union(new_files) # add that to source_file
Upvotes: 1