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

Python实现TXT文件转指定JSON格式时跳行漏读问题如何解决

问题解决方法

错误原因

你的代码出现跳行是因为使用了itertools.zip_longest(*[f_in]*2)逻辑,该写法会每次从文件中读取2行,仅使用第一行作为x的值,第二行直接被丢弃,刚好你的文本中数字行和空行交替出现,就会导致间隔的数字行被丢弃。

修改方案

不需要使用itertools相关逻辑,直接遍历文件所有行,过滤掉空行后生成对应格式即可,修改后代码如下:

import json

# 先读取所有非空行
valid_lines = []
with open('sample.txt', 'r') as f_in:
    for line in f_in:
        content = line.strip()
        if content: # 跳过空行
            valid_lines.append(content)

# 输出目标格式
with open('formated.json', 'w') as f_out:
    for idx, line_val in enumerate(valid_lines):
        record = {
            "x": line_val,
            "y": "a"
        }
        f_out.write(json.dumps(record, indent=2))
        # 非最后一条记录加逗号换行
        if idx != len(valid_lines) - 1:
            f_out.write(',\n')

运行上述代码即可得到你期望的输出格式,同时也避免了最后多余的尾逗号不符合JSON规范的问题。


内容的提问来源于stack exchange,提问作者Z-Zip

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:15:05