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:
JavaScript
x
14
14
1
import os
2
3
def main():
4
#search for file in your dir
5
for file in os.listdir('path/to/dir'):
6
if file.endswith('.jpegs'):
7
#if extension = ".jpegs" -> move your file
8
os.replace("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
9
10
if __name__ == '__main__':
11
#infinite loop
12
while True:
13
main()
14
and this other is for copy file:
JavaScript
1
22
22
1
import os
2
import shutil
3
4
def main():
5
#search for file in your dir
6
for file in os.listdir('path/to/dir'):
7
#if extension = ".jpegs"
8
if file.endswith('.jpegs'):
9
#source file
10
src = f'path/to/dir/{file}'
11
#destination
12
dest = f'path/to/new/destination/for/{file}'
13
#if it does not exist
14
if not os.path.isfile(dest):
15
#copy file
16
shutil.copyfile(src, dest)
17
18
if __name__ == '__main__':
19
#infinite loop
20
while True:
21
main()
22
CTRL+C
in your terminal for end script