如何修改文本文件才能读取?

问题描述 投票:0回答:2

我想在程序中读取一个文本文件。但是我只想在更改文本文件时才读取该文件。

如果文本文件未更改,那么我不想再次阅读。我尝试了一些操作,但是每3秒钟会读取一次文本文件。

def load():
  f = open('input.txt', 'r')
  file = f.read()
  f.close()
  print(file)
  file = int(file)
  print file
  Timer(3,load).start()
load()

python python-3.x
2个回答
0
投票
import os

filename = "input.txt"
obj = os.stat(filename)
print("modified time: {}".format(obj.st_mtime))

0
投票

您可以使用内置的Python库来实现相同的效果。

基于现有代码:

import time
import os.path
mod_time = time.ctime(os.path.getmtime('input.txt'))
def load():
    global mod_time
    new_mtime = time.ctime(os.path.getmtime('input.txt'))
    if new_mtime != mod_time:
        mod_time = new_mtime
        f = open('input.txt', 'r')
        file = f.read()
        f.close()
        print(file)
        file = int(file)
        print file
    Timer(3,load).start()
load()

[如果您注意到,mod_time最终会跟踪您要读取的input.txt文件的更改修改时间。

© www.soinside.com 2019 - 2024. All rights reserved.