在for循环中迭代相同的json(dict)文件两次

在for循环中迭代相同的json(dict)文件两次

问题描述:

所以我有json文件,我需要为不同的文件获取两个不同的字符串。 第一个是要去的文件,因为它应该但第二个不是。在for循环中迭代相同的json(dict)文件两次

我做了我的研究,我知道我需要将文件指针移回去开始。但我只是不知道该怎么做。因为我刚刚得到这个错误:

Traceback (most recent call last): 
    File "v4.py", line 65, in <module> 
    data.seek(0,0) 
AttributeError: 'str' object has no attribute 'seek' 

试图把它与.seek(0)

with open('idd.json', 'r') as data_file:  
    data = json.load(data_file) 

with open('id.txt','w') as outfile: 
    for data, lokaatio in data[0].items(): 
     if data=='id': 
      print(lokaatio, file=outfile) 

data.seek(0,0) 

with open('type.txt','w') as outfiles: 
    for data, type in data[0].items(): 
     if data=='fileType': 
      print(type, file=outfiles) 

如何移动JSON(字典)文件来启动新的搜索回迁时..


更新:

现在,没有错误,但第二个文件保持空白。 (感谢您缩短的代码行!)

python找不到fileType。剩下的唯一解决方案是否在我的文件中出现问题?它看起来大约是这样的:

[{'ID': 'BDB-0bxGag9AL_C4xB0hlM', 'VERSIONNUMBER':1},{ '宽度mm':127.0, 'heightIn':5.0, '宽度':1500} ,{ 'documentId': 'xmp.483a0ab5','的fileType': 'JPEG', '高mm':127.0}, '许可': 'rx--'}]

+0

问题出在'用于数据,lokaatio in ...':您重新使用数据变量名,以便旧数据被覆盖。它原本是一本字典,不需要寻求(0)。 – RemcoGerlich

+0

'data'不是文件对象。您只需在'for'循环中重新使用该名称即可将其绑定到一个字符串。 –

+0

您可以在从文件加载数据后添加'print(data)'并发布结果吗? – kvorobiev

线后

data = json.load(data_file) 

变量data将包含dict而不是file。而你的代码(除了data.seek(0,0)这是错误的)几乎没有问题。您的问题在于:

for data, lokaatio in data[0].items(): 

您重新定义了data变量。试着用

with open('id.txt','w') as outfile: 
    for d, lokaatio in data[0].items(): 
     if d=='id': 
      print(lokaatio, file=outfile) 

而且替换此,遍历dict是不必要的(感谢@让·弗朗索瓦·法布尔评论的)。你可以通过键获取元素。

with open('id.txt','w') as outfile: 
    print(data.get('id', ''), file=outfile) 

同为第二循环

with open('type.txt','w') as outfiles: 
    print(data.get('fileType', ''), file=outfiles) 

你所有的代码可以与

with open('idd.json', 'r') as data_file:  
    data = json.load(data_file) 

with open('id.txt','w') as idfile, open('type.txt','w') as typefile: 
    print(data.get('id', ''), file=idfile) 
    print(data.get('fileType', ''), file=typefile) 
+1

为什么循环字典项目来搜索密钥?这似乎是有限的。不需要循环。 –

+0

@ Jean-FrançoisFabre同意,感谢您的评论。将更新回答 – kvorobiev

+0

@ E.W查看我的更新。并添加新的问题描述到你的问题。 – kvorobiev

没有必要循环两次更换,只需用一个简单的if,elif的发言和开放你的两个文件在一起。像这样:

with open('idd.json', 'r') as data_file:  
    data = json.load(data_file) 

with open('id.txt','w') as outfile1, open('type.txt','w') as outfile2 : 
    for key,value in data[0].items(): # or is your dict in data.items()? 
     if key =='id': 
      print(value, file=outfile1) 
     elif key =='fileType': 
      print(value, file=outfile2)