简体   繁体   中英

How can i read a text file again and again in every 1 sec?

I want to read a text file as my input. But that text file will change again and again. So i need to read that same file again and again. How can i do that?

I know how to read a text file in python.

file=open('input.txt','r').read()

How about the following:

import time
while True:
  try:
    with open('input.txt','r') as f:
      file=f.read()
  except:
    pass
  time.sleep(1)

It can cause problems, because you're using asynchronous access. Someone might be writing to that file when you try to open it for reading and you may get garbage. You need to have some form of synchronization between the different processes using that file. Take a look at https://docs.python.org/3/library/multiprocessing.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM