python中的文件读取
我需要读取如下文件:
config = {
'name': 'hello',
'see?': 'world'
}
使用名称等键并查看? ,但我不想对脚本中的值进行硬编码。以及在这种情况下如何处理更深层的嵌套。该文件可能包含更多像这样的部分,我如何在运行时识别“名称”属于哪个部分。
I need to read the file like below:
config = {
'name': 'hello',
'see?': 'world'
}
using keys like name and see? ,but I don't want to hard code the values in script.And how to deal with more deep nesting in this case.The file may contain more sections like this how can I recognize that 'name' belongs to which section at runtime.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您将结构编码为 JSON 数据,正如我认为您想要的并且您在示例中所做的那样,您只需要在文件中写入和读取结构。
例如:
配置文件已保存
配置文件已重新加载
If you encode your structure as JSON data, as I think you want and you did in the example, you just need to write and read the structure in a file.
As an example:
Configuration file saved
Configuration file reloaded
该文件看起来像有效的 python。如果您可以将其重命名为
file.py
您可以只使用:否则,该文件可能是 JSON。请参阅http://docs.python.org/library/json.html
That file looks like valid python. If you can rename it
file.py
You could just use:Otherwise, the file could be JSON. See http://docs.python.org/library/json.html
听起来你想要一个配置文件?该格式是否已经定义或者您正在创建它?如果您只需要从文件中读取选项:
http://docs.python.org/library /configparser.html
处理 INI 格式。如果您已经有上述格式的文件,您能判断它是否是 JSON 格式吗?如果是这样,也有一个模块。
Sounds like you want a config file? Has the format been defined already or are you creating it? If you just need to read options from a file there's:
http://docs.python.org/library/configparser.html
which handles the INI format. If you already have a file in the format above can you tell if it's a JSON format? If so there's a module for that too.
看来你的配置格式是有效的 python 或 JSON,它有一个内置的 python 解析器。有关详细信息,请参阅 http://docs.python.org/library/json.html 。如果您尝试导入有效的 python 文件作为配置,只需使用
import
。It seems your config format is either valid python or JSON, which has a built-in parser in python. See http://docs.python.org/library/json.html for more information. If you're trying to import a valid python file as config just use
import
.