使用多线程写入JSONL文件。 参数: - file_path (str): 文件路径。 - data (list): 要写入的JSON数据。 - mode (str): 写入模式,默认为 'a'(追加模式),可以选择 'w'(覆盖模式)。 - chunk_size (int): 数据大小阈值,单位为字节。 - encoding (str): 写入文件的编码格式,默认为 'utf-8'。
(file_path, data, mode, chunk_size, encoding='utf-8')
| 448 | |
| 449 | |
| 450 | def write_jsonl_multithread(file_path, data, mode, chunk_size, encoding='utf-8'): |
| 451 | """ |
| 452 | 使用多线程写入JSONL文件。 |
| 453 | |
| 454 | 参数: |
| 455 | - file_path (str): 文件路径。 |
| 456 | - data (list): 要写入的JSON数据。 |
| 457 | - mode (str): 写入模式,默认为 'a'(追加模式),可以选择 'w'(覆盖模式)。 |
| 458 | - chunk_size (int): 数据大小阈值,单位为字节。 |
| 459 | - encoding (str): 写入文件的编码格式,默认为 'utf-8'。 |
| 460 | """ |
| 461 | chunks = [data[i:i + chunk_size] for i in range(0, len(data), chunk_size)] |
| 462 | cpu_count = os.cpu_count() // 2 # 限制使用一半的CPU核心数 |
| 463 | num_threads = min(cpu_count, len(chunks)) |
| 464 | |
| 465 | logger.info(f"分割数据为 {len(chunks)} 个块进行多线程写入") |
| 466 | |
| 467 | with ThreadPoolExecutor(max_workers=num_threads) as executor: |
| 468 | futures = [executor.submit(write_jsonl_chunk, file_path, chunk, mode, encoding) for chunk in chunks] |
| 469 | for future in tqdm(futures, desc="写入JSONL文件进度"): |
| 470 | future.result() |
| 471 | |
| 472 | |
| 473 | def write_jsonl_chunk(file_path, chunk, mode, encoding='utf-8'): |