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.

levi
  • 22,001
  • 7
  • 73
  • 74
  • 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. – lightalchemist Feb 04 '15 at 05:45

4 Answers4

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()
Marcin
  • 215,873
  • 14
  • 235
  • 294
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.

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
Community
  • 1
  • 1
Vivek Sable
  • 9,938
  • 3
  • 40
  • 56
-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
  • 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. – PaulMcG Feb 04 '15 at 06:13
  • `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()`. – PaulMcG Feb 04 '15 at 06:14
  • we can use `if db.has_key("God")` instead – nshermione Feb 04 '15 at 08:14
  • Unless you are targeting Python 2.2 or older, please don't use the deprecated method `has_key`, see comments on VivekSable's answer. – PaulMcG Feb 05 '15 at 04:59