无法使用Python
读取文件中的所有数据在test.txt里面有:
{'God': {u'user1@localhost': {}, u'user2@localhost': {}, u'user3@localhost': {}}}
,代码是:
# coding: utf-8
def read_file(filename):
data=None
try:
fp = file(filename)
data = fp.read()
fp.close()
except: pass
return data
def read():
file = 'test.txt'
db = eval(read_file(file))
if "God" in db:
for x in db["God"]:
data = x
#print(x) $$ it'll print all data True but I do not need it, I will put instructions inside and I do not need to be repeated.
print(x) # $$ print just 1 data from file
try: read()
except: pass
如何让它读取文件中的所有数据 thx。
答案 0 :(得分:2)
要从文本文件中读取所有数据,只需使用文件对象的read方法,例如
with open('test.txt','r') as f:
file_content = f.read()
答案 1 :(得分:0)
而不是使用file()尝试open() 事实上你应该养成这个习惯。 在所有情况下,开发人员都被指示使用open()而不是file()。
答案 2 :(得分:0)
with
和open
方法阅读文件。eval
文件内容,以将内容转换为字典格式。has_key
检查God key
是否存在。 [使用in
'has_key()' or 'in'? method to get all keys of
上帝值词典。代码:
def readFile(filepath):
with open(filepath, "rb") as fp:
data = fp.read()
db = eval(data)
if "God" in db:
godkeys= db["God"].keys()
print "godkeys:-", godkeys
print "Data:", ','.join(godkeys)
filepath = '/home/infogrid/Desktop/input1.txt'
readFile(filepath)
输出:
$ python workspace/vtestproject/study/test.py
godkeys:- [u'user3@localhost', u'user2@localhost', u'user1@localhost']
Data: user3@localhost,user2@localhost,user1@localhost
答案 3 :(得分:-1)
db = eval(read_file(file))
db是一本字典。字典是许多对关键和价值的集合。要检查某个键是否在dict中,我们应该使用keys()函数,如下所示:
if "God" in db.keys():
另外,要获取dict中的所有数据,我们只需使用items()来获取键和值对。
for key, value in db["God"].items():
print "Key", key
print "Value", value