使用多线程写入文本文件。 参数: - file_path (str): 文件路径。 - data (str): 要写入的数据。 - mode (str): 写入模式,默认为 'a'(追加模式),可以选择 'w'(覆盖模式)。 - chunk_size (int): 数据大小阈值,单位为字节。 - encoding (str): 写入文件的编码格式,默认为 'utf-8'。
(file_path, data, mode, chunk_size, encoding='utf-8')
| 388 | |
| 389 | |
| 390 | def write_txt_multithread(file_path, data, mode, chunk_size, encoding='utf-8'): |
| 391 | """ |
| 392 | 使用多线程写入文本文件。 |
| 393 | |
| 394 | 参数: |
| 395 | - file_path (str): 文件路径。 |
| 396 | - data (str): 要写入的数据。 |
| 397 | - mode (str): 写入模式,默认为 'a'(追加模式),可以选择 'w'(覆盖模式)。 |
| 398 | - chunk_size (int): 数据大小阈值,单位为字节。 |
| 399 | - encoding (str): 写入文件的编码格式,默认为 'utf-8'。 |
| 400 | """ |
| 401 | chunks = [data[i:i + chunk_size] for i in range(0, len(data), chunk_size)] |
| 402 | cpu_count = os.cpu_count() // 2 # 限制使用一半的CPU核心数 |
| 403 | num_threads = min(cpu_count, len(chunks)) |
| 404 | |
| 405 | logger.info(f"分割数据为 {len(chunks)} 个块进行多线程写入") |
| 406 | |
| 407 | with ThreadPoolExecutor(max_workers=num_threads) as executor: |
| 408 | futures = [executor.submit(write_chunk, file_path, chunk, mode, encoding) for chunk in chunks] |
| 409 | for future in tqdm(futures, desc="写入文件进度"): |
| 410 | future.result() |
| 411 | |
| 412 | |
| 413 | def write_chunk(file_path, chunk, mode, encoding='utf-8'): |