读取JSONL文件,支持多线程处理。 参数: - file_path (str): 文件路径。 - chunk_size (int): 文件大小阈值,单位为字节。 - line_threshold (int): 行数阈值,超过此值使用多线程。 - encoding (str): 文件编码格式,默认为 'utf-8'。 返回: - list: 读取的JSONL文件内容。
(file_path, chunk_size, line_threshold, encoding='utf-8')
| 294 | |
| 295 | |
| 296 | def read_jsonl(file_path, chunk_size, line_threshold, encoding='utf-8'): |
| 297 | """ |
| 298 | 读取JSONL文件,支持多线程处理。 |
| 299 | |
| 300 | 参数: |
| 301 | - file_path (str): 文件路径。 |
| 302 | - chunk_size (int): 文件大小阈值,单位为字节。 |
| 303 | - line_threshold (int): 行数阈值,超过此值使用多线程。 |
| 304 | - encoding (str): 文件编码格式,默认为 'utf-8'。 |
| 305 | |
| 306 | 返回: |
| 307 | - list: 读取的JSONL文件内容。 |
| 308 | """ |
| 309 | file_size = os.path.getsize(file_path) |
| 310 | num_lines = sum(1 for _ in open(file_path, 'r', encoding=encoding)) |
| 311 | |
| 312 | if file_size > chunk_size or num_lines > line_threshold: |
| 313 | logger.info(f"文件 {file_path} 较大,启用多线程读取") |
| 314 | return read_jsonl_multithread(file_path, chunk_size, num_lines, encoding) |
| 315 | else: |
| 316 | logger.info(f"读取JSONL文件: {file_path}") |
| 317 | with open(file_path, 'r', encoding=encoding) as f: |
| 318 | return [json.loads(line) for line in f] |
| 319 | |
| 320 | |
| 321 | def read_jsonl_multithread(file_path, chunk_size, num_lines, encoding='utf-8'): |
no test coverage detected