读取一个配置文件,里面都是 k=v 这样的格式。放到 dict 里,有木有 pythonic 点的方式?

2016-05-19 19:19:05 +08:00
 aias

比如:

application.mode=dev
3599 次点击
所在节点    Python
17 条回复
mckelvin
2016-05-19 19:25:43 +08:00
配置文件最好选一种标准化的格式,比如 ini, json, yaml, 再用标准化的方式去读取(而非自己去按行读,按等号分割),这样就优雅了吧。
fy
2016-05-19 19:26:49 +08:00
dict([x[:-1].split('=') for x in f.readlines()])
tongle
2016-05-19 19:27:36 +08:00
ConfigParser 也许你需要这个
imn1
2016-05-19 19:28:45 +08:00
configparser — Configuration file parser

This module provides the ConfigParser class which implements a basic configuration language which provides a structure similar to what ’ s found in Microsoft Windows INI files. You can use this to write Python programs which can be customized by end users easily.
haozhang
2016-05-19 19:43:02 +08:00
hocon
aias
2016-05-19 20:24:18 +08:00
@fy hello ,又是你~~
fy
2016-05-19 20:30:24 +08:00
@aias 魔性的狗头
yongzhong
2016-05-19 20:35:14 +08:00
ConfigParser +1
qw7692336
2016-05-19 23:35:53 +08:00
@aias 魔性的狗头
ayaseangle
2016-05-20 00:15:06 +08:00
这像是 Java 的 properties 文件。。。。
hrong
2016-05-20 08:20:23 +08:00
java 有 getBundle(),连 bash 都有 source,为毛 Python 就木有原生?不可能啊。。。我不懂 Python ,你们别拍我
ryanking8215
2016-05-20 09:00:48 +08:00
@hrong 是不可能啊。 import 模块或文件不就行啦?!
bramblex
2016-05-20 09:58:51 +08:00
一行代码就解决的问题楼上一群人非要引进来一个库,用不用顺便再 require 一个 leftpad ?
araraloren
2016-05-20 10:23:36 +08:00
...同意楼上说的,一句话就能解决的事情,为啥要引入库。。
linuxchild
2016-05-20 18:02:17 +08:00
2L 的已经很 pythonic 了
RadishWind
2016-05-21 08:42:45 +08:00
直接把配置文件写成 dict 的格式, import
lianghui
2016-05-23 13:22:24 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/279845

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX