python程序启动后复制文件

Copy files with python program after it starts

我需要一个 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)

试试这个代码,我稍微修改了你的代码。它将文件从源目录复制到目标目录。一旦它复制了一个文件,即使它在源或目标中被删除,它也不会复制该文件。它只会复制新添加的文件。

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