2016-11-16 68 views
1

我有一个文件。它看起来像它由词典组成。从字典文件中打印键码

我试图从文件中打印出密钥。

import json 
tweet = json.load 


file = open("CRP.txt",'r') 
lines = file.readlines() 
file.close() 

print file.keys() 

for line in lines: 
    if line.find("id"): 
     print tweet.keys("CRP.txt") 
     print keys.id 

当我运行这个,这个弹出

AttributeError:'file' has no attribute 'key' 

回答

1

您已经导入JSON,但在错误的方式使用它。正确的方法使用起来会像:

import json 

with open("CRP.txt",'r') as json_file: # Efficient way to open files 
    data = json.load(json_file) # Load the file object 
    for key in data: # Iterate over all the keys 
     print key 

如果您还需要相应的值,重复这样的:

for key, value in data.items(): 
    print key, value 
+0

谢谢!我有一个想法问题。可以说该文件包含多个字典。你需要做什么来打印字典的所有键? – user

+0

@user:这是完全不同的问题。你应该把它作为一个单独的问题来提出 –

0

AttributeError:'file' has no attribute 'key'错误是行print file.keys()。 open()在你的情况下返回一个文件对象,即“file”。这个文件对象没有keys()方法。

你可能想看看这个关于如何使用keys()https://www.tutorialspoint.com/python/dictionary_keys.htm的更多信息。