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

查看:195
本文介绍了重新读取一个打开的文件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天全站免登陆