[Tutor] Monitoring directories
Nathan D'Elboux
nathan.delboux at gmail.com
Thu Feb 13 20:02:50 EST 2020
________________________________
Hi Pythonistas!
I have a little script below that copies files from a directory and
all of its sub directories over to a target dir. The target dir doesnt
have any sub dir's and is exactly how i want it. The copy checks if
the file in the source dir exists in the target dir and then copies if
it doesnt.
Problem is is that i have another utility monitoring that target dir
moving the files out to process them further so as it processes them
the target dir will always be empty thus coping every file from source
folder over and over depending on interval i run the script
What i would like to do is change my below script from checking if
sourcedir filename exists in target dir, is to change it so it
monitors the source dir and copies the newest files over to the target
dir.
As this script is invoked currently via a cron job im not familiar
with what i would need to do to make this python script monitor in
daemon mode or how it would know the newest files and the fact it
haunt already copied them over.
The script i have already is below. Just looking for feedback on how i
should improve this. Would using something like Pyinotify work best
in this situation?
import shutil
import os
targetdir = "/home/target_dir"
sourcedir = "/home/source/"
dirlist = os.listdir(sourcedir)
for x in dirlist :
directory = sourcedir + x + '/'
filelist = os.listdir(directory)
for file in filelist :
if not os.path.exists(os.path.join(targetdir,file)):
shutil.copy(directory+file,targetdir)
Thanks in advance for any advice
Nathan
More information about the Tutor
mailing list