1

How can I define my worker to do stuff for the first 4 first lines from the test.txt file and then go into the next worker and continue with the next 4 items in list (so 5-8) and so on. (3rd worker 9-12).

Code:

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 contains the numbers from 1 to 12:

1
2
3
...
12

output should look like:

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

Also main() should stop returning after there are no more items in list, so in this example it would stop the loop after the 12 item from list.

request
  • 140
  • 1
  • 9

2 Answers2

2

You might need this worker() function, check this answer to iterate a list of items with index:

def worker():
    for idx, Item in enumerate(Mylist):
        if idx % N == 0:
            print("Done Session")
            time.sleep(2)
        print(Item)
Jun Zhou
  • 947
  • 1
  • 3
  • 17
1

You can use range and read specific indexes of List

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()   
xszym
  • 706
  • 1
  • 4
  • 9