简体   繁体   中英

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)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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