简体   繁体   English

根据文件内容创建哈希表

[英]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. with语句确保无论发生什么情况都将自动关闭文件,并且如果打开失败,则程序将引发正确的异常。 The json.load function directoly loads data from an open file handle. json.load函数直接从打开的文件句柄加载数据。

Additionally, I strongly suggest reading and understanding the Python tutorial. 另外,我强烈建议阅读和理解Python教程。 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 其中第一个字符串是文件的路径,第二个字符串是模式: r = read, w = write, a = append

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

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