重新读取一个打开的文件Python

Ben*_*ght 14 python testing file

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

所以:

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

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

Joh*_*ooy 21

要么seek到文件的开头

with open(...) as fin:
    fin.read()   # read first time
    fin.seek(0)  # offset of 0
    fin.read()   # read again
Run Code Online (Sandbox Code Playgroud)

或者再次打开文件(我更喜欢这种方式,因为你保持文件打开一小时,在传递之间什么都不做)

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

with open(...) as fin:
    fin.read()   # read again
Run Code Online (Sandbox Code Playgroud)

把它放在一起

while True:
    with open(...) as fin:
        for line in fin:
            # do something 
    time.sleep(3600)
Run Code Online (Sandbox Code Playgroud)


Kon*_*nev 17

您可以通过以下方式将光标移动到文件的开头:

file.seek(0)
Run Code Online (Sandbox Code Playgroud)

然后你就可以成功阅读它了.