从python中的JSON数据中保存许多文件文本

时间:2018-06-03 01:39:15

标签: python json syntax-error

我是python中的新手。我想创建一个新数组来保存我的JSON数据的每个部分的类型。再次检查,如果任何部分在该数组中有一种类型,那么保存在另一个文件文本调用' type0.txt' ,' type1.txt',....所以这是我的代码。

from __future__ import print_function 
import json
# Remember to check the path to articles.json relative to this file before executing

with open('articles.json') as json_data:
   # Load JSON
   articles = json.load(json_data)
   print(len(articles), "Articles loaded succesfully")
   # Loop through every article in the json file

   typeLabel = []
   for article in articles:
       typeL = article["type"]
       typeLabel.append(typeL)

   typeLabel = set(typeLabel)
   typeLabel = list(set(typeLabel))

   seen = set()
   resultType = []
   for item in typeLabel:
      if item not in seen:
        seen.add(item)
        resultType.append(item)

   for article in articles
       x = 0
       for i in range(0,len(resultType) - 1):
           if article["type"] = resultType[i]:
            filePathName = resultType[i] + x + '.txt'
               with open(filePathName, 'w') as reader:
                   json.dump(article["content"], reader)
            x += 1

    pass

首先我收到错误

  

文章中的文章                             ^ SyntaxError:语法无效

然后我不确定我写的是否是正确的语法,所以你可以帮我修改我的代码吗?非常感谢!!

1 个答案:

答案 0 :(得分:0)

for article in articles:

你忘记了结肠。

@comment 您正在尝试将不同类型连接在一起。您应该使用字符串格式。 format方法将在幕后找到不同对象的字符串表示。

filePathName = '{}{}.txt'.format(resultType[i], x)

而不是

filePathName = resultType[i] + x + '.txt'