WEshruth
WEshruth

Reputation: 787

Create hash table from the contents of a file

How can I open a text file, read the contents of the file and create a hash table from this content? So far I have tried:

import json

json_data = open(/home/azoi/Downloads/yes/1.txt).read()

data = json.loads(json_data)
pprint(data)

Upvotes: 0

Views: 908

Answers (2)

hochl
hochl

Reputation: 12960

I suggest this solution:

import json

with open("/home/azoi/Downloads/yes/1.txt") as f:
    data=json.load(f)
    pprint(data)

The with statement ensures that your file is automatically closed whatever happens and that your program throws the correct exception if the open fails. The json.load function directoly loads data from an open file handle.

Additionally, I strongly suggest reading and understanding the Python tutorial. It's essential reading and won't take too long.

Upvotes: 4

juankysmith
juankysmith

Reputation: 12458

To open a file you have to use the open statment correctly, something like:

json_data=open('/home/azoi/Downloads/yes/1.txt','r')

where the first string is the path to the file and the second is the mode: r = read, w = write, a = append

Upvotes: 0

Related Questions