With this code, I look at a source directory and copy it to the destination. But when I add a new file to the source directory, the copying is not done. And I want a file to be copied every second. This code is doing batch copying. Can you help me solve these two problems?
import os,os.path
import shutil
from os import listdir
from os.path import isfile, join
my_path = 'source_path'
target = 'target_path'
onlyfiles = [f for f in listdir(my_path ) if isfile(join(my_path , f))]
while True:
for file in onlyfiles:
if file.endswith(".gz"):
a = my_path + file
b = target + file
shutil.copy(a, b)
time.sleep(1)
>Solution :
Ultimately, this solution can make it work
import shutil
import time
from pathlib import Path
import glob
my_path = 'source_path'
target = 'target_path'
onlyfiles = glob.glob(my_path+'/*.gz')
for file in onlyfiles:
shutil.copy(file, target + '/'+ Path(file).name)
time.sleep(1)