"將一組字串加入JSON檔案"

2024-05-13 21:45:22 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我想把数组中的元素添加到一个JSON文件中,我想让数组中的每个元素都在自己的行中,我现在有这个

while i < num:
    name1= tweet_list[i]
    name1 = re.sub(r'(https|http)?:\/\/(\w|\.|\/|\?|\=|\&|\%)*\b|\n|@', '', name1, flags=re.MULTILINE)
    print name1
    judge = input("1 pos, 2 neg, 3 skip: ")
    if judge == 1:
        pos_name.append(name1)
    elif judge == 2:
        neg_name.append(name1)
    i += 1

    with open("pos_names.json", "a") as p:
        json.dump(pos_name, p)
    with open("neg_names.json", "a") as n:
        json.dump(neg_name,n)

此代码将所有元素放在一行上,但由于某些原因,文件中的前面总是有空元素[]


Tags: 文件nameposrejson元素namesas
1条回答
网友
1楼 · 发布于 2024-05-13 21:45:22

这是因为您在append模式下打开输出文件("a"标志作为open的第二个参数),这意味着写入文件的任何内容都将附加到当前内容中;在while循环的每个迭代中将列表转储到文件(这也是为什么前面有空列表-在最初的几个迭代中pos_name和/或neg_name可能仍然是空列表)。尝试以写模式"w"打开文件,并在循环完成后写入json转储。像这样:

while i < num:
    # etc. what you had before

# this after the loop
with open("pos_names.json", "w") as p:
    json.dump(pos_name, p)
with open("neg_names.json", "w") as n:
    json.dump(neg_name,n)

请注意,这仍然会在一行上输出所有内容—如果您需要的话,可以使用indentkwarg to json.dump来漂亮地打印它(有关用法示例,请参见python docs。)下面的示例(ipython session-json.dumps输出到stdout而不是文件):

In [8]: import json

In [9]: print(json.dumps(['one', 'two', 'three']))
["one", "two", "three"]

In [10]: print(json.dumps(['one', 'two', 'three'], indent=2))
[
  "one",
  "two",
  "three"
]

相关问题 更多 >