当使用json.dump生成多个文件时,有没有一种方法可以省略第一个文件的创建?[关闭]

qacovj5a  于 5个月前  发布在  其他
关注(0)|答案(2)|浏览(96)

已关闭。此问题需要details or clarity。目前不接受回答。
**要改进此问题吗?**通过editing this post添加详细信息并阐明问题。

27天前关闭。
Improve this question
我正在使用json.dump生成多个JSON文件。JSON是这样的:

[
{"any": 2023},
{
"dia": 24,
"mes": 1,
"any": 2023,
"mes_referencia": 12,
"any_referencia": 2022,
"calendari_nom": "CTH"
}]

字符串
但我需要的是第一部分{"any":2023}不生成JSON文件。
我使用以下代码,其中json_output是JSON脚本:

data = json.loads(json_output)

for i, d in enumerate(data, 1):
    with open(f"data_out_{i}.json", "w") as f_out:
        json.dump(d, f_out, indent=4)


有没有办法在创建文件之前省略第一个文件的创建?

oaxa6hgo

oaxa6hgo1#

如果它总是第一项,你可以在循环中检查,即。

for i, d in enumerate(data, 1):
    if i == 1:
        continue
    ...

字符串
或者直接跳过第一项,对data进行切片:

for i, d in enumerate(data[1:], 1):
    ...


或者,如果你想跳过任何只有一个any键的项目:

for i, d in enumerate(data, 1):
    if set(d) == {'any'}:
        continue
    ...


最后,如果您希望能够跳过项目,并且编号序列中没有间隙,则可以使用单独的itertools.count对其进行编号:

counter = itertools.count(1)
for d in data:
    if "foo" in d:  # skip this
        continue
    if not d:  # skip an empty entry
        continue
    # (etc...)
    i = next(counter)
    with open(f"data_out_{i}.json", "w") as f_out:
        json.dump(d, f_out, indent=4)

nc1teljy

nc1teljy2#

我用一个If子句解决了这个问题,就像这样:

import json

    data = json.loads(json_output)
    
    for i, d in enumerate(data, 0):
        if i==0:
            None
        else:
            with open(f"data_out_{i}.json", "w") as f_out:
                json.dump(d, f_out, indent=4)

字符串
这样,第一部分就不会生成。
谢谢

相关问题