[英]Reading file line by line with Python in multithreading is reading only the first line
请帮帮我
python 仅读取我的 txt 文件中的第一行并在线程中忽略 rest
我仍然无法弄清楚,请检查我下面的代码
我希望每个线程逐行读取,例如
线程 1 读取第 1 行,
线程 2 读取第 2 行
线程 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!")
在您打开的每个线程中,您再次打开文件,从而从头开始读取。 每个线程都在打开文件并读取第一行并完成。 如果您在做一些特定的事情时需要帮助,我会尽力帮助您。
如果要在每个线程中打印文件:
def test_logic():
myfile = open("prox.txt", 'r')
line = myfile.readline()
while(line != ''):
user, password = line.split(':')
print(user + password)
line = myfile.readline()
如果要在每个线程中打印不同的行:
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!")
不确定这是否是最好的解决方案,但这应该可行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.