aias
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
mckelvin
   1
mckelvin  
   2016 年 5 月 19 日   ❤️ 1
配置文件最好选一种标准化的格式,比如 ini, json, yaml, 再用标准化的方式去读取(而非自己去按行读,按等号分割),这样就优雅了吧。
fy
   2
fy  
   2016 年 5 月 19 日
dict([x[:-1].split('=') for x in f.readlines()])
tongle
   3
tongle  
   2016 年 5 月 19 日
ConfigParser 也许你需要这个
imn1
   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.
haozhang
   5
haozhang  
   2016 年 5 月 19 日 via iPhone
hocon
aias
   6
aias  
OP
   2016 年 5 月 19 日
@fy hello ,又是你~~
fy
   7
fy  
   2016 年 5 月 19 日
@aias 魔性的狗头
yongzhong
   8
yongzhong  
   2016 年 5 月 19 日
ConfigParser +1
qw7692336
   9
qw7692336  
   2016 年 5 月 19 日
@aias 魔性的狗头
ayaseangle
   10
ayaseangle  
   2016 年 5 月 20 日 via Android
这像是 Java 的 properties 文件。。。。
hrong
   11
hrong  
   2016 年 5 月 20 日 via Android
java 有 getBundle(),连 bash 都有 source,为毛 Python 就木有原生?不可能啊。。。我不懂 Python ,你们别拍我
ryanking8215
   12
ryanking8215  
   2016 年 5 月 20 日
@hrong 是不可能啊。 import 模块或文件不就行啦?!
bramblex
   13
bramblex  
   2016 年 5 月 20 日
一行代码就解决的问题楼上一群人非要引进来一个库,用不用顺便再 require 一个 leftpad ?
araraloren
   14
araraloren  
   2016 年 5 月 20 日
...同意楼上说的,一句话就能解决的事情,为啥要引入库。。
linuxchild
   15
linuxchild  
   2016 年 5 月 20 日
2L 的已经很 pythonic 了
RadishWind
   16
RadishWind  
   2016 年 5 月 21 日
直接把配置文件写成 dict 的格式, import
lianghui
   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
© 2026 V2EX · 72ms · 3.9.8.5