Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中保存JSON数据中的许多文本文件_Python_Json_Syntax Error - Fatal编程技术网

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

在python中保存JSON数据中的许多文本文件,python,json,syntax-error,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

我是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:无效语法

然后我不确定我写的其余的是否是正确的语法,所以你能帮我修复我的代码吗。非常感谢

for article in articles:
你忘了冒号

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

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

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

我有下一个错误:filePathName=resultType[I]+x+'.txt'类型错误:必须是str,而不是int我如何才能像type0.txt那样保存它;type1.txt with type是类型数组中的字符串吗?太好了!我就知道。我只添加一个def。它成功了。很抱歉,你能帮我一个问题吗。我正在尝试保存不带双引号的文件。我搜索并尝试了很多次,但都没有成功。>使用codecs.open(filePathName,'w',encoding='utf-8')作为读卡器:>dataOut=article[“content”]。替换('','')>json.dump(dataOut,读卡器,确保ascii=False)