我有一个代码,它将以附加模式打开一个.text文件,生成一个随机字符串,并在一定时间间隔内将这些字符串附加到文件中。
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程序编写。如果没有要读取的新行,则它将等待新行,但它不会自行停止。因此,当有新行可用时,我只想打印新行。
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程序的要求执行操作,请帮助!!!