写入JSON文件,支持多线程处理。 参数: - file_path (str): 文件路径。 - data (list): 要写入的JSON数据。 - mode (str): 写入模式,默认为 'a'(追加模式),可以选择 'w'(覆盖模式)。 - encoding (str): 写入文件的编码格式,默认为 'utf-8'。
(file_path, data, mode, encoding='utf-8')
| 543 | |
| 544 | |
| 545 | def write_json(file_path, data, mode, encoding='utf-8'): |
| 546 | """ |
| 547 | 写入JSON文件,支持多线程处理。 |
| 548 | |
| 549 | 参数: |
| 550 | - file_path (str): 文件路径。 |
| 551 | - data (list): 要写入的JSON数据。 |
| 552 | - mode (str): 写入模式,默认为 'a'(追加模式),可以选择 'w'(覆盖模式)。 |
| 553 | - encoding (str): 写入文件的编码格式,默认为 'utf-8'。 |
| 554 | """ |
| 555 | if mode == 'a' and os.path.exists(file_path): |
| 556 | with open(file_path, 'r+', encoding=encoding) as f: |
| 557 | existing_data = json.load(f) |
| 558 | existing_data.extend(data) |
| 559 | f.seek(0) |
| 560 | json.dump(existing_data, f, ensure_ascii=False, indent=4) |
| 561 | else: |
| 562 | logger.info(f"写入JSON文件: {file_path}") |
| 563 | with open(file_path, mode, encoding=encoding) as f: |
| 564 | json.dump(data, f, ensure_ascii=False, indent=4) |
| 565 | |
| 566 | |
| 567 | def write_yaml(file_path, data, mode, encoding='utf-8'): |