Pything 线程,如何让 3 个线程读取 csv 文件

问题描述 投票:0回答:1

如何让 3 个线程读取 csv 文件,但有一个我无法弄清楚的问题,例如在此列表中: 1 2 3 4 5 6

我怎样才能让线程像这样读: 线程1:1 线程2:2 线程 3: 3 线程 1: 4 线程 2: 5 主题 3:6

我希望他们继续前进,现在发生的是这样的: 线程1:1 线程 1:2 线程 1: 3 线程 1: 4 线程 1: 5 线程 1:6

线程2:1 线程2:2 线程 2: 3 线程 2: 4 线程 2: 5 线程 2: 6 等等...

我想让他们一起逐行阅读,你们可以帮我吗?

import threading
import csv

# Function to read and print rows from the CSV file
def read_csv(filename):
    with open(filename, 'r') as csv_file:
        reader = csv.reader(csv_file)
        for row in reader:
            print(f"Thread {threading.current_thread().name} - CSV Row: {row}")

# Specify the CSV file
csv_filename = 'your_csv_file.csv'

# Create and start three threads
threads = []
for i in range(3):
    thread = threading.Thread(target=read_csv, args=(csv_filename,))
    threads.append(thread)
    thread.start()

# Wait for all threads to finish
for thread in threads:
    thread.join()
python multithreading csv row
1个回答
0
投票

我想让他们一起逐行阅读,你们可以帮我吗?

© www.soinside.com 2019 - 2024. All rights reserved.