Re-read an open file Python

后端 未结 2 1017
陌清茗
陌清茗 2020-12-07 00:25

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 th

相关标签:
2条回答
  • 2020-12-07 01:09

    Either seek to the beginning of the file

    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
    

    Putting this together

    while True:
        with open(...) as fin:
            for line in fin:
                # do something 
        time.sleep(3600)
    
    0 讨论(0)
  • 2020-12-07 01:23

    You can move the cursor to the beginning of the file the following way:

    file.seek(0)
    

    Then you can successfully read it.

    0 讨论(0)
提交回复
热议问题