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

一个程序在某个过程的每第15次迭代后生成输出文本文件,命名为output.txt。这样做会覆盖上一个output.txt文件。然而,我希望保留这些文件,并且无法在程序中修改文件名。
我能否运行一个脚本与该程序一起监控输出目录,并将output.txt文件移动并重命名到另一个目录中?

1迭代是什么意思?如果这是您的自定义程序,最好修改它以便能够处理这个问题。如果您不知道如何做到这一点,应该在Stack Overflow上提出这个问题。 - kos
这个程序运行一个循环然后保存输出文件。我需要一个文件管理器。我得到了一个线索,希望它能起作用。谢谢您的关注。 - Sajid Iqbal
3个回答

首先安装软件包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的目录中,并且重命名为带有日期和时间后缀的新文件,这样可以确保不覆盖旧文件,并且你还可以知道该文件创建的时间和日期。

下面的脚本将移动和重命名出现在指定目录(dr1)中的任何文件。它将文件重命名为output_1.txt,output_2.txt等。脚本会“主动”检查目标名称是否已存在于目录2中(而不是从“盲目”选择的范围),因此您可以随时启动和停止脚本,而无需担心覆盖现有文件。
由于它给输出文件一个唯一的名称,并且根据定义不会覆盖现有文件,所以目标目录可以与源目录相同。
如何使用:
  • 将脚本复制到一个空文件中,保存为rename_save.py
  • 重要步骤:在头部设置检查新文件的时间间隔。确保时间间隔比新文件出现的间隔(15次迭代所需的时间)要短(多得多),否则新文件将在最后一个文件移动之前创建。
  • 同样在头部,设置源目录和要保存重命名文件的目录的路径。
  • 通过以下命令运行:

    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 "在$2中发现新文件或更改的文件\"output.txt\""
        mv "$2/$filename" "$backup_folder/${filename%.*}.$(date +'%Y-%m-%d_%H:%M:%S').${filename##*.}"
    fi
    
  • 使其可执行:

    chmod +x <watch_output_scriptзљ„е®Њж•ґи·Їеѕ„>
    
  • 监视您的输出文件夹:

    inoticoming "$HOME/output" <watch_output_scriptзљ„е®Њж•ґи·Їеѕ„> {} "$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