V2EX › Python
读取一个配置文件,里面都是 k=v 这样的格式。放到 dict 里,有木有 pythonic 点的方式?
By aias at 2016 年 5 月 19 日 · 4802 次点击比如:
application.mode=dev
17 条回复 • 2016-05-23 13:22:24 +08:00
|
1
mckelvin 2016 年 5 月 19 日 配置文件最好选一种标准化的格式,比如 ini, json, yaml, 再用标准化的方式去读取(而非自己去按行读,按等号分割),这样就优雅了吧。
|
|
2
fy 2016 年 5 月 19 日
dict([x[:-1].split('=') for x in f.readlines()])
|
|
3
tongle 2016 年 5 月 19 日
ConfigParser 也许你需要这个
|
|
4
imn1 2016 年 5 月 19 日
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. |
|
5
haozhang 2016 年 5 月 19 日 via iPhone
hocon
|
|
8
yongzhong 2016 年 5 月 19 日
ConfigParser +1
|
|
10
ayaseangle 2016 年 5 月 20 日 via Android
这像是 Java 的 properties 文件。。。。
|
|
11
hrong 2016 年 5 月 20 日 via Android
java 有 getBundle(),连 bash 都有 source,为毛 Python 就木有原生?不可能啊。。。我不懂 Python ,你们别拍我
|
|
12
ryanking8215 2016 年 5 月 20 日
@hrong 是不可能啊。 import 模块或文件不就行啦?!
|
|
13
bramblex 2016 年 5 月 20 日
一行代码就解决的问题楼上一群人非要引进来一个库,用不用顺便再 require 一个 leftpad ?
|
|
14
araraloren 2016 年 5 月 20 日
...同意楼上说的,一句话就能解决的事情,为啥要引入库。。
|
|
15
linuxchild 2016 年 5 月 20 日
2L 的已经很 pythonic 了
|
|
16
RadishWind 2016 年 5 月 21 日
直接把配置文件写成 dict 的格式, import
|
|
17
lianghui 2016 年 5 月 23 日
|
推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide