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

joh*_*345 4 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
Run Code Online (Sandbox Code Playgroud)

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

for i in os.stat(f).st_mtime:
Run Code Online (Sandbox Code Playgroud)

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

我想了解在我继续之前导致这种情况的原因

Wil*_*ill 6

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
Run Code Online (Sandbox Code Playgroud)

我相信.无论你是在与迭代os.walk(),加入root和f将产生的绝对路径IIRC.

有关更多信息,请参阅此处:http://www.tutorialspoint.com/python/os_walk.htm


Pad*_*ham 5

您需要解压,将文件加入根目录并进行比较:

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))
Run Code Online (Sandbox Code Playgroud)

os.stat(filename).st_mtime返回一个无法迭代的时间,您需要将该时间与当前时间进行比较,time.time()它本身返回自纪元以来的秒数,因此您需要将两者之间的差异与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()
Run Code Online (Sandbox Code Playgroud)

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