写入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')
| 425 | |
| 426 | |
| 427 | def write_jsonl(file_path, data, mode, chunk_size, encoding='utf-8'): |
| 428 | """ |
| 429 | 写入JSONL文件,支持多线程处理。 |
| 430 | |
| 431 | 参数: |
| 432 | - file_path (str): 文件路径。 |
| 433 | - data (list): 要写入的JSON数据。 |
| 434 | - mode (str): 写入模式,默认为 'a'(追加模式),可以选择 'w'(覆盖模式)。 |
| 435 | - chunk_size (int): 数据大小阈值,单位为字节。 |
| 436 | - encoding (str): 写入文件的编码格式,默认为 'utf-8'。 |
| 437 | """ |
| 438 | data_size = len(data) |
| 439 | if data_size > chunk_size: |
| 440 | logger.info(f"数据较大,启用多线程写入") |
| 441 | write_jsonl_multithread(file_path, data, mode, chunk_size, encoding) |
| 442 | else: |
| 443 | logger.info(f"写入JSONL文件: {file_path}") |
| 444 | with open(file_path, mode, encoding=encoding) as f: |
| 445 | for entry in data: |
| 446 | json.dump(entry, f, ensure_ascii=False) |
| 447 | f.write('\n') |
| 448 | |
| 449 | |
| 450 | def write_jsonl_multithread(file_path, data, mode, chunk_size, encoding='utf-8'): |
no test coverage detected