Search code examples
pythonmultithreadingline

Reading file line by line with Python in multithreading is reading only the first line


Please help me out

python only reads the first line in my txt file & ignore the rest while in threading

i still can't figure it out, please check my code below

I want each thread to read the line by line e.g

thread 1 reads line 1 ,

thread 2 reads line 2

thread 3 reads line 3




import threading

def test_logic():
   myfile = open("prox.txt", 'r')



   user, password =  myfile.readline().split(':')



   print(user + password )




N = 5   # Number of browsers to spawn
thread_list = list()

# Start test
for i in range(N):
   t = threading.Thread(name='Test {}'.format(i), target=test_logic)
   t.start()
   time.sleep(1)
   print ("t.name +  started!")

   thread_list.append(t)

# Wait for all thre<ads to complete
for thread in thread_list:
   thread.join()

print("Test completed!")


Solution

  • In every thread that you open you open the file again, thus starting reading from its begining. Each thread is opening the file and reading the first line and finishing. If you need help in doing something specific ask and i'll try to help you out.

    If you want to print the file in each thread:

    def test_logic():
        myfile = open("prox.txt", 'r')
    
        line = myfile.readline()
        while(line != ''):
            user, password =  line.split(':')
    
            print(user + password)
    
            line = myfile.readline()
    

    If you want to print in each thread a different line:

    import threading
    import time
    
    def test_logic(file): # ***Changed this function***
    
        line = myfile.readline()
        if line != '':
            user, password =  line.split(':')
    
            print(user + password )
    
    N = 5   # Number of browsers to spawn
    thread_list = list()
    myfile = open("prox.txt", 'r') # ***Opened file at the begining***
    # Start test
    for i in range(N):
        t = threading.Thread(args=(myfile,), name='Test {}'.format(i), target=test_logic) # ***Passed file as an argument***
        t.start()
        time.sleep(1)
        print ("t.name +  started!")
    
        thread_list.append(t)
    
    # Wait for all thre<ads to complete
    for thread in thread_list:
        thread.join()
    
    print("Test completed!")
    

    Not sure if this is the greatest solution but this should work