重新读取打开的文件 Python [英] Re-read an open file Python

查看:28
本文介绍了重新读取打开的文件 Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本可以读取一个文件,然后根据该文件完成测试,但是我遇到了一个问题,因为该文件在一小时后重新加载,并且我无法让脚本在该时间点或之后重新读取该文件及时.

I have a script that reads a file and then completes tests based on that file however I am running into a problem because the file reloads after one hour and I cannot get the script to re-read the file after or at that point in time.

所以:

  • 获取要阅读的新文件
  • 读取文件
  • 对文件进行测试
  • 获取要阅读的新文件(具有相同名称 - 但如果它是解决方案的一部分,则可以更改)
  • 读取新文件
  • 对新文件执行相同的测试

谁能建议一种让 Python 重新读取文件的方法?

Can anyone suggest a way to get Python to re-read the file?

推荐答案

要么seek到文件开头

with open(...) as fin:
    fin.read()   # read first time
    fin.seek(0)  # offset of 0
    fin.read()   # read again

或再次打开文件(我更喜欢这种方式,因为否则您将文件打开一个小时,两次通过之间什么都不做)

or open the file again (I'd prefer this way since you are otherwise keeping the file open for an hour doing nothing between passes)

with open(...) as fin:
    fin.read()   # read first time

with open(...) as fin:
    fin.read()   # read again

把它放在一起

while True:
    with open(...) as fin:
        for line in fin:
            # do something 
    time.sleep(3600)

这篇关于重新读取打开的文件 Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆