如何监控目录中的新文件并将其移动/重命名为另一个目录?

在某个进程的每第15次迭代之后,程序生成输出文本文件,名为output.txt 。 这样做,它会覆盖最后一个output.txt 。 我想保留文件,但我无法修改程序中的文件名。

我可以运行一些脚本,以及监视输出目录的程序,并将output.txt文件移动并重命名到另一个目录中吗?

首先安装包inotify-tools

 sudo apt-get install inotify-tools 

bash脚本会有所帮助

 #! /bin/bash folder=~/Desktop/abc cdate=$(date +"%Y-%m-%d-%H:%M") inotifywait -m -q -e create -r --format '%:e %w%f' $folder | while read file do mv ~/Desktop/abc/output.txt ~/Desktop/Old_abc/${cdate}-output.txt done 

这个脚本意味着什么:

这将监视文件夹~/Desktop/abc所以每当在里面创建一个文件时,它就会将名为output.txt的文件移动到目录~/Desktop/Old_abc并重命名,提供t的日期和时间的后缀他是新文件,这肯定不会覆盖旧文件,你也知道这个文件是在什么时间和日期创建的

下面的脚本将移动并重命名可能出现在已定义目录( dr1 )中的任何文件。 它重命名文件,如: output_1.txt ,output_2.txt`等。如果目标名称已存在于目录2中(而不是“盲目”选择的范围),脚本将“主动”显示,因此您可以启动和停止脚本在任何时候都没有覆盖现有文件的风险。

由于它为输出文件提供了唯一的名称,并且根据定义不会覆盖现有文件,因此目标目录可以与源目录相同。

如何使用

  • 将脚本复制到空文件中,将其另存为rename_save.py
  • 重要步骤:在head部分中,设置检查新文件的时间间隔。 确保时间间隔(很多)短于新文件出现的时间间隔(15次迭代所用的时间),否则将在移动最后一个文件之前创建新文件。
  • 同样在head部分中,设置源目录和要将重命名文件保存到的目录的路径。
  • 通过命令运行它:

     python3 /path/to/rename_save.py 

    而另一个(迭代)脚本正在运行

剧本

 #!/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) 
  • 安装包inoticoming

     sudo apt-get install inoticoming 
  • 创建包装器脚本watch_output

     #!/bin/bash backup_folder="$HOME/backups" filename="$1" mkdir -p "$backup_folder" if [ "$filename" == "output.txt" ] then echo "New or changed file \"output.txt\" in $2" mv "$2/$filename" "$backup_folder/${filename%.*}.$(date +'%Y-%m-%d_%H:%M:%S').${filename##*.}" fi 
  • 使其可执行:

     chmod +x  
  • 观察文件夹输出文件夹:

     inoticoming "$HOME/output"  {} "$HOME/output" \; 

例:

 $ killall inoticoming $ inoticoming "$HOME/output" ./watch_output {} "$HOME/output" \; $ touch $HOME/output/output.txt $ ls -log $HOME/backups total 0 -rw-rw-r-- 1 0 Mai 13 14:32 output.2015-05-13_14:32:10.txt