如何等待文本文件写入,逐行读取更改并打印?

时间:2020-04-18 14:58:52

标签: python python-3.x python-asyncio semaphore file-handling

我有一个代码,它将以附加模式打开一个.text文件,生成一个随机字符串,并在一定时间间隔内将这些字符串附加到文件中。

程序:Random_Generation

import os
import sys
import string
import random
import time

class RandomCreation():
    def __init__(self, path):
        self.path = path

    def string_generator(self, size):
        chars = string.ascii_uppercase + string.ascii_lowercase
        return ''.join(random.choice(chars) for _ in range(size))

if __name__ == '__main__':
    path = os.path.realpath(sys.argv[1])
    try:
        while True:
            random_cration = RandomCreation(path)
            data = random_cration.string_generator(10)
            f = open(f'{path}/try_file.txt', 'a+')
            f.write(data +"\n")
            print('Successfully Appended')
            time.sleep(2)
    except KeyboardInterrupt:
        f.close()
        print('Exiting......')
        exit()

该程序运行完美。

我想编写另一个程序(称为File_Handling),它将打开相同的.text文件并逐行读取文件。该程序取决于上面提到的名为Random_Generation的程序。该File_Handling程序将等待,直到生成文本文件。生成文本文件后,它将逐行读取文件并打印内容,而仍由Random_Generation程序编写。如果没有要读取的新行,则它将等待新行,但它不会自行停止。因此,当有新行可用时,我只想打印新行。

程序:File_Handling

import sys
import os
import os.path
import time

path = os.path.realpath(sys.argv[1])
filename = f'{path}/try_file.txt'
while not os.path.exists(filename):
    time.sleep(1)
if os.path.exists(filename):
    file = open(filename, "r")
    for num, line in enumerate(file, 1):
        print(f'{num}: {line}')
    file.close()

两个代码都并行运行。程序File_Handling的条件:

  • 如果文本文件为空,则它将等待新行的可用
  • 如果文本文件中存在某些行,则它将逐行读取这些行,直到文件结尾。
  • 到达文件末尾后,它将等待新行的可用性。
  • 它永远不会回到以前阅读过的那些行。
  • 写作和阅读程序都不同步。
  • 可以随时写。
  • 唯一的事实是写后读取将一直持续到文件末尾。

要达到目标,它必然需要信号量,甚至可能是异步的。但是我应该合并它们吗?

我无法按照File_Handling程序的要求执行操作,请帮助!!!

0 个答案:

没有答案
相关问题