从字典文件中打印密钥

时间:2016-11-16 00:44:29

标签: python dictionary

我有一个档案。它看起来像是由字典组成的。

我正在尝试打印文件中的密钥。

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'

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

您可能需要查看此内容,了解有关如何使用键()https://www.tutorialspoint.com/python/dictionary_keys.htm的更多信息。