1

can't read all data from file useing Python

inside test.txt there is :

{'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.

1
  • 2
    As general advice, never eval what you read in from file. Big security risk. Store/convert your data to a more appropriate form if necessary, but never eval. Commented Feb 4, 2015 at 5:45

4 Answers 4

2

To read all data from a text file just use read method of a file object, e.g.

with open('test.txt','r') as f:
    file_content = f.read()
Sign up to request clarification or add additional context in comments.

Comments

0
  1. Read File using with and open method.
  2. eval file content to get content into dictionary format.
  3. Use has_key to check God key is present or not. [use in 'has_key()' or 'in'?
  4. Use 'keys()method to get all keys of God value` dictionary.
  5. use 'join()` string method

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

5 Comments

hi, much time taken for to do ctrl+k
has_key has been deprecated for years - preferred form is if "God" in db:
@PaulMcGuire: ok. but can you give more information on it.
@VivekSable - see details in this question stackoverflow.com/questions/1323410/has-key-or-in
@mr.somebody: Working, then upvote/accept answer :), just kidding :)
0

instead of using file() try open() in fact you should get in the habit of that. Developers are directed to use open() instead of file() in all cases.

1 Comment

same thing file() or open() print just 1 data
-1
db = eval(read_file(file))

db is a dictionary. 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:

if "God" in db.keys():

Also, to get all data in dict, we just use items() to get pair of key and value.

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

4 Comments

In line with other commenters' cautions about using eval, safer to use ast.literal_eval, which does not have the same risks of accidental or malicious command injection.
if "God" in db: is sufficient to check for a matching key, without incurring the overhead of building the list of keys by calling keys().
we can use if db.has_key("God") instead
Unless you are targeting Python 2.2 or older, please don't use the deprecated method has_key, see comments on VivekSable's answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.