Rin
Rin

Reputation: 81

How to read to file simultaneously using Thread

I have two file employeename and employee address read both the file and want expected output :

Jhon Pitroda
Mumbai
Rinkal
Hubali

I write code but output is not actual as I want with using the threads how can I achive ,I am new in the Programming.
can anyone help me, Thank you in advance.

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()

my output :

Jhon Pitroda
Rinkal
Mumbai
Hubli



Upvotes: 0

Views: 660

Answers (1)

Berkay Tekin Öz
Berkay Tekin Öz

Reputation: 207

Your write_to_temp_file() function seems to be causing the problem. Since you have 2 threads trying to write to same file this I think what happens: thread1 and thread2 reads from their given files and tries to write to the temp_file.txt. But here is the deal, since the program is threaded, the output of the file will depend on which thread runs at which time. This means scheduling of threads will alter the output of the file. If you want to append one file to another you should avoid threads. Instead of running this operation threaded you should run these operations in a single thread and that will guarantee your expected output. Also if you want that threads write to the file one line after another, you may want to use Events. That way your threads will signal each other so they will always have the exact execution order.

Upvotes: 1

Related Questions