You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用绝对路径仍触发FileNotFoundError,Python拆分JSON文件问题求解

问题原因与解决方案

核心报错原因

Python的open()函数写入文件时,仅会自动生成目标文件,不会主动创建路径中不存在的上层目录。你代码中输出文件的父目录C:\Users\flipp\Downloads\smaller files如果没有提前手动创建,就会触发FileNotFoundError。

其他排查项

  • 确认输入文件的文件名完全匹配,避免Windows隐藏后缀名导致实际文件名为signalmedia-1m.json.txt之类的异常情况
  • 确认运行代码的账号对decompressed和smaller files目录有读写权限

修复后代码

import os
import json

# 读取源文件
with open(os.path.join(r'C:\Users\flipp\Downloads\decompressed', 'signalmedia-1m.json'), 'r', encoding='utf-8') as f1:
    ll = [json.loads(line.strip()) for line in f1.readlines()]

print(len(ll))

size_of_the_split = 2000
total = len(ll) // size_of_the_split

print(total + 1)

# 提前创建输出目录,exist_ok=True表示目录已存在时不报错
output_dir = r'C:\Users\flipp\Downloads\smaller files'
os.makedirs(output_dir, exist_ok=True)

for i in range(total + 1):
    # 用os.path.join拼接路径,避免字符串拼接出现格式错误
    output_path = os.path.join(output_dir, f"usedData{i+1}.json")
    json.dump(
        ll[i * size_of_the_split : (i + 1) * size_of_the_split],
        open(output_path, 'w', encoding='utf8'),
        ensure_ascii=False,
        indent=True
    )

内容的提问来源于stack exchange,提问作者james immanuel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 23:51:02