The script below will move and rename any file that might appear in a defined directory (dr1
). It renames the files like: output_1.txt
, output_2.txt` etc. The script looks "actively" if the targeted name already exists in directory 2 (not from a "blindly" chosen range), so you can start and stop the script at any time without the risk of overwriting existing files.
Since it gives the output files a unique name, and does by definition not overwrite existing files, the targeted directory can be the same as the source directory.
How to use
The script
#!/usr/bin/env python3
import shutil
import os
import time
#--- set the time interval to check for new files (in seconds) below
# this interval should be smaller than the interval new files appear!
t = 1
#--- set the source directory (dr1) and target directory (dr2)
dr1 = "/path/to/source_directory"
dr2 = "/path/to/target_directory"
name = "output_"; extension = ".txt"
newname = lambda n: dr2+"/"+name+str(n)+extension
while True:
newfiles = os.listdir(dr1)
for file in newfiles:
source = dr1+"/"+file
n = 1; target = newname(n)
while os.path.exists(target):
n = n+1; target = newname(n)
shutil.move(source, target)
time.sleep(t)