如何在最后5分钟内更改文件

  • 本文关键字:文件 5分钟 最后 python
  • 更新时间 :
  • 英文 :


需要遍历当前目录并在最后5分钟内修改文件。我才刚刚开始,这就是我到目前为止

#!/usr/bin/python
import os,sys,time
dir = os.getcwd() 
print dir

for f in os.walk(dir):
    for i in os.stat(f).st_mtime:
    print i

当我运行这个时,我得到这个错误

for i in os.stat(f).st_mtime:

TypeError:强制为Unicode:需要字符串或缓冲区,找到元组

在我继续

之前,我想了解是什么导致了这种情况

os.walk()生成元组,您正试图使用字符串。你想要类似的东西:

for root, dirs, files in walk(wav_root):
    for f in files:
        filename = root + f
        # Now use filename to call stat().st_mtime

我相信。使用os.walk()迭代时,无论您身在何处,连接rootf都将生成绝对路径IIRC。

查看此处了解更多信息:http://www.tutorialspoint.com/python/os_walk.htm

您需要解压缩,将文件连接到根目录并比较:

import os, time
_dir = os.getcwd()
files = (fle for rt, _, f in os.walk(_dir) for fle in f if time.time() - os.stat(
    os.path.join(rt, fle)).st_mtime < 300)
print(list(files))

os.stat(filename).st_mtime返回一个无法迭代的时间,您需要将该时间与当前时间进行比较,time.time()本身返回自epoch以来的秒数,因此您需要将time.time() - os.stat(os.path.join(rt, fle)).st_mtime之间的差值与以秒为单位的分钟数进行比较,即在您的情况下为300。

如果你正在监视目录,你可能会发现看门狗很有用,文档中的例子正是你想要的:

import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler
if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s - %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')
    path = sys.argv[1] if len(sys.argv) > 1 else '.'
    event_handler = LoggingEventHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

它递归地检查当前目录中的文件更改,并将任何更改记录到控制台。

尝试使用'os'、'glob'和'time'库:

import os
import glob
import time
file_list = glob.glob("C:\path_to_files\*.")
for file in file_list:
    if (int(time.time()) - int(os.stat(file).st_mtime) < 300):
        # Do something with this file

最新更新