【问题标题】:Python multithreading output to CSV filePython多线程输出到CSV文件
【发布时间】:2021-02-24 00:01:34
【问题描述】:

我是 python 多线程的新手,我刚刚尝试了以下解决方案。问题是每次输出文件都是空的,找不到问题:

from concurrent.futures import ThreadPoolExecutor
import threading
csv_writer_lock = threading.Lock()

def get_data(searchKey):
  #do some data scraping
  l1.append(data)
  l2.append(data)
  l = l1 + l2
  with csv_writer_lock:
    with open("results.csv", mode="a") as f1:
      writer = csv.writer(f1, delimiter=",")
      writer.writerows(l)
    f1.close()
  return l

def set_up_threads(urls):
  try:
    
    with ThreadPoolExecutor(max_workers=5) as executor:
        result = executor.map(get_data, urls["links"],timeout = 300)
  except Exception:
      print("Error")
  return result


df = pd.read_csv(file_path)
final = set_up_threads(df)

有人可以指出此解决方案中的错误方向吗?谢谢!

【问题讨论】:

  • 可能是 stackoverflow.com/questions/3976711/… 的副本? (tl;dr 确保在 CSVWriter 上调用 flush)
  • 不确定为什么要调用 f1.close(),因为在退出 with 子句时它已经被调用了,除此之外,我认为 csv 没有理由为空
  • 如果您在尝试写入之前执行print(l),它是否包含任何数据? :)

标签: python python-3.x multithreading csv


【解决方案1】:

我能够使用@dtanabe 技巧解决它,我必须添加 flush。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 2020-01-24
    • 2021-05-17
    • 2021-12-21
    • 1970-01-01
    • 2014-07-28
    相关资源
    最近更新 更多