简体   繁体   English

在多线程中使用 Python 逐行读取文件是只读取第一行

[英]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 python 仅读取我的 txt 文件中的第一行并在线程中忽略 rest

i still can't figure it out, please check my code below我仍然无法弄清楚,请检查我下面的代码

I want each thread to read the line by line eg我希望每个线程逐行读取,例如

thread 1 reads line 1,线程 1 读取第 1 行,

thread 2 reads line 2线程 2 读取第 2 行

thread 3 reads line 3线程 3 读取第 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!")

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不确定这是否是最好的解决方案,但这应该可行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM