首页 > 解决方案 > 如何使用线程同时读取文件

问题描述

我有两个文件employeename 和employee address 读取这两个文件并想要预期的输出:

Jhon Pitroda
Mumbai
Rinkal
Hubali

我编写代码但输出不是实际的,因为我想要使用线程如何实现,我是编程新手。
任何人都可以帮助我,提前谢谢你。

from time import sleep
from threading import *

class EmpInfoMerger(Thread):
# write data from text file to temp file
    def write_to_temp_file(self,file_path,mode):
        with open(file_path,mode) as filein:
            with open('temp_file.txt', 'a+') as fileout:
                for line in filein:
                    fileout.write(line)
                    print(line)
                    sleep(1)

        filein.close()
        fileout.close()

    def write_to_file(self,file_path,mode):
        read_file = open("temp_file.txt", "r+")
        data_input = read_file.read()
        # A output file to print temp data to file
        write_file = open(file_path, mode)
        write_file.write(data_input)

        print("file contents are written from temp_file  to output_file and temp_file contents are deleted ")
        read_file.truncate(0)
        write_file.close()
        read_file.close()

    def run(self):
        empName = EmpInfoMerger()
        thread1 = Thread(empName.write_to_temp_file("empName_file.txt","r"))

        empAdd = EmpInfoMerger()
        thread2 = Thread(empAdd.write_to_temp_file("empaddress.txt","r"))

        output = EmpInfoMerger()
        thread3 = Thread(output.write_to_file("output_file.txt", "w"))

        thread1.start()
        thread2.start()
        thread3.start()

        thread1.join()
        # sleep(1)
        thread2.join()
        # sleep(1)
        thread3.join()

obj = EmpInfoMerger()
obj.run()

我的输出:

Jhon Pitroda
Rinkal
Mumbai
Hubli



标签: pythonpython-3.xmultithreading

解决方案


您的write_to_temp_file()功能似乎导致了问题。由于您有 2 个线程试图写入同一个文件,因此我认为会发生什么:thread1thread2从他们给定的文件中读取并尝试写入temp_file.txt. 但这里是交易,因为程序是线程的,文件的输出将取决于哪个线程在哪个时间运行。这意味着线程的调度将改变文件的输出。如果要将一个文件附加到另一个文件,则应避免使用线程。您应该在单个线程中运行这些操作,而不是线程运行此操作,这将保证您的预期输出。此外,如果您希望线程一行接一行地写入文件,您可能需要使用事件. 这样,您的线程将相互发出信号,因此它们将始终具有确切的执行顺序。


推荐阅读