简体   繁体   English

使用python从文件读取数据

[英]read data from file with python

can't read all data from file useing Python 无法使用Python从文件读取所有数据

inside test.txt there is : 在test.txt中有:

{'God': {u'user1@localhost': {}, u'user2@localhost': {}, u'user3@localhost': {}}}

and the code is : 和代码是:

# 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

how can I let it to read all data from file 我如何让它从文件中读取所有数据

thx. 谢谢。

To read all data from a text file just use read method of a file object, eg 要从文本文件中读取所有数据,只需使用文件对象的read方法,例如

with open('test.txt','r') as f:
    file_content = f.read()

instead of using file() try open() in fact you should get in the habit of that. 而不是使用file()尝试使用open()实际上,您应该养成这种习惯。 Developers are directed to use open() instead of file() in all cases. 在所有情况下,开发人员都必须使用open()而不是file()。

  1. Read File using with and open method. 使用withopen方法读取文件。
  2. eval file content to get content into dictionary format. eval文件内容以将内容转换为字典格式。
  3. Use has_key to check God key is present or not. 使用has_key检查是否存在God key [use in 'has_key()' or 'in'? [ in 'has_key()'或'in'中使用?
  4. Use 'keys() method to get all keys of God value` dictionary. 使用'keys() method to get all keys of God value`字典的method to get all keys of
  5. use 'join()` string method 使用'join()`字符串方法

code: 码:

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)

output: 输出:

$ python  workspace/vtestproject/study/test.py
godkeys:- [u'user3@localhost', u'user2@localhost', u'user1@localhost']
Data: user3@localhost,user2@localhost,user1@localhost
db = eval(read_file(file))

db is a dictionary. db是字典。 Dictionary is collection of many pairs of key and value. 词典是许多键和值对的集合。 To check if some key is in dict, we should use keys() function as below: 要检查字典中是否包含某些键,我们应使用keys()函数,如下所示:

if "God" in db.keys():

Also, to get all data in dict, we just use items() to get pair of key and value. 另外,要获取dict中的所有数据,我们只需使用items()来获取键和值对。

for key, value in db["God"].items():
    print "Key", key
    print "Value", value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM