不在Python文件中写入

问题描述 投票:0回答:1

我有一个 Threaded 类,我试图在其中追加数据,但它没有执行任何操作,没有错误,没有成功。以下是代码的基本结构

from threading import Thread

class ABC:
   def func1(user):
       # Do processing
       func2(lst) # lst Generated in processing

   def func2(lst):
        thrd_list = []
        for ele in lst:
            x = Thread(target=func3, args(ele, ))
            x.start()
            thrd_list.append(x)
        for thrd in thrd_list:
            thrd.join()

   def func3(ele):
       # Do some stuff and if successful write to file
       OUTPUT.write(f"{ele}\n")

with open("users.txt", "r") as f:
     users = f.readlines()
OUTPUT = open("result.txt", "a")
thrd_list = []
for user in users: 
    x = Thread(target=func1, args(user, ))
    x.start()
    thrd_list.append(x)
for thrd in thrd_list:
    thrd.join()
OUTPUT.close()

在遇到 OUTPUT.close() 时正在写入数据。我希望它随着运行而附加,这样就不会因崩溃或错误而丢失数据

python multithreading file python-multithreading file-writing
1个回答
0
投票
from threading import Thread

class ABC:
    @staticmethod
    def func1(user):
        ABC.func2(user)

    @staticmethod
    def func2(lst):
        thrd_list = []
        for ele in lst:
            x = Thread(target=ABC.func3, args=(ele, ))
            x.start()
            thrd_list.append(x)
        for thrd in thrd_list:
            thrd.join()

    @staticmethod
    def func3(ele):
        # Do some stuff and if successful write to file
        with open("result.txt", "a") as OUTPUT:
            OUTPUT.write(f"{ele}\n")

if __name__ == "__main__":
    with open("users.txt", "r") as f:
        users = f.readlines()

    thrd_list = []
    for user in users:
        x = Thread(target=ABC.func1, args=(user.strip(), ))character
        x.start()
        thrd_list.append(x)
    for thrd in thrd_list:
        thrd.join()
© www.soinside.com 2019 - 2024. All rights reserved.