I made this python code for testing purposes. The idea behind it is to read the rows of a csv file, assign data to variables and print those varibales using threads. However, I would like the function to read the csv file row by row for each thread but I didn't find how to do it...
The csv file looks like this :
name lastname
1 John B.
2 Alex G.
3 Myriam R.
4 Paul V.
5 Julia L.
6 Margot M.
Here's the code :
import csv
import threading
class main():
def print_names():
with open('names.csv', 'r') as csv_file:
csv_reader = csv.DictReader(csv_file)
for row in csv_reader:
data = name, lastname = row['name'], row['lastname']
screenlock.acquire()
print(name, lastname)
screenlock.release()
if __name__ == '__main__':
screenlock = threading.BoundedSemaphore(1)
with open('names.csv', 'r') as csv_file:
csv_reader = csv.DictReader(csv_file)
rows_count = len(list(csv_reader))
threads = []
for _ in range(rows_count):
t = threading.Thread(target=main.print_names)
threads.append(t)
t.start()
for thread in threads:
thread.join()
The current output is :
Margot M.
Margot M.
Margot M.
Margot M.
Margot M.
Margot M.
But I would like to get this output :
John B.
Alex G.
Myriam R.
Paul V.
Julia L.
Margot M.
PS : Sorry if my question isn't really understandable, its my first post here.