Python:将文本文件拆分为多个工作会话



如何定义我的工作线程为test.txt文件中的前 4 行执行操作,然后进入下一个工作线程并继续处理列表中的下 4 个项目(所以 5-8(依此类推。(第三名工人9-12(。

法典:

import time
with open("test.txt", "r") as f:
Mylist = f.readlines()
N = 4
def worker():
for Item in Mylist:
#Do Stuff
print(Item)
print("Done Session")    
time.sleep(2)

def main():
worker()
worker()
worker()
return main()
main()   

test.txt包含从 1 到 12 的数字:

1
2
3
...
12

输出应如下所示:

1
2
3
4
Done Session
5
6
7
8
Done Session
9
10
11
12
Done Session

此外,main()应该在列表中没有更多项目后停止返回,因此在此示例中,它将在列表中的 12 个项目之后停止循环。

您可能需要此 worker(( 函数,请查看此答案以迭代带有索引的项目列表:

def worker():
for idx, Item in enumerate(Mylist):
if idx % N == 0:
print("Done Session")
time.sleep(2)
print(Item)

您可以使用范围并读取列表的特定索引

import time
with open("test.txt", "r") as f:
Mylist = f.readlines()
N = 4
def worker(index_of_worker):
for x in range(index_of_worker*4, index_of_worker*4+N):
print(Mylist[x])
print("Done Session")    
time.sleep(2)

def main():
worker(0)
worker(1)
worker(2)
return main()

main()   

最新更新