Skip to content
Advertisement

Automatically and continuously copy files of a certain extension created in source folder and not present in output with Python

I have a program that creates .jpegs in a folder and deletes them after a very short time. I’d like to automatically copy those files to another folder as they are created and before they are deleted. I tried using robocopy but couldn’t manage. How can I do this with Python?

Advertisement

Answer

this script analyse your dir and move file if finded:

import os

def main():
    #search for file in your dir
    for file in os.listdir('path/to/dir'):
        if file.endswith('.jpegs'):
            #if extension = ".jpegs" -> move your file
            os.replace("path/to/current/file.foo", "path/to/new/destination/for/file.foo")

if __name__ == '__main__':
    #infinite loop
    while True:
        main()

and this other is for copy file:

import os
import shutil

def main():
    #search for file in your dir
    for file in os.listdir('path/to/dir'):
        #if extension = ".jpegs"
        if file.endswith('.jpegs'):
            #source file
            src = f'path/to/dir/{file}'
            #destination
            dest = f'path/to/new/destination/for/{file}'
            #if it does not exist
            if not os.path.isfile(dest):
                #copy file
                shutil.copyfile(src, dest)

if __name__ == '__main__':
    #infinite loop
    while True:
        main()

CTRL+C in your terminal for end script

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement