我需要一个Python脚本,该脚本每5分钟监视一次目录更改,并仅复制添加的文件。不要从源目录复制现有文件。程序启动后复制文件。当我删除目标上的文件时,程序会复制文件。我的python版本是3.6.32
听到的是我的代码:
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)
答案 0 :(得分:0)
尝试此代码,我对您的代码做了一些修改。它将文件从源目录复制到目标。一旦复制了一个文件,即使在源或目标中将其删除,也不会复制该文件。它将仅复制新添加的文件。
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