我会使用ConfigParser模块,它为您的示例生成一些非常易读且用户可编辑的输出:
[bob] colour_scheme: blue british: yes [joe] color_scheme: that's 'color', silly! british: no
以下代码将生成上面的配置文件,然后将其打印出来:
import sys
from ConfigParser import *
c = ConfigParser()
c.add_section("bob")
c.set("bob", "colour_scheme", "blue")
c.set("bob", "british", str(True))
c.add_section("joe")
c.set("joe", "color_scheme", "that's 'color', silly!")
c.set("joe", "british", str(False))
c.write(sys.stdout) # this outputs the configuration to stdout
# you could put a file-handle here instead
for section in c.sections(): # this is how you read the options back in
print section
for option in c.options(section):
print "\t", option, "=", c.get(section, option)
print c.get("bob", "british") # To access the "british" attribute for bob directly
Run Code Online (Sandbox Code Playgroud)
请注意,ConfigParser仅支持字符串,因此您必须按照我上面的布尔值进行转换.请参阅effbot以了解基础知识.
我没有解决哪一个最好的问题.如果你想处理文本文件,我会考虑ConfigParser -module.你可以尝试的另一个是simplejson或yaml.您还可以考虑一个真正的数据库表.
例如,你可以有一个名为userattrs的表,有三列:
如果只有少数,您可以将它们存储到cookie中以便快速检索.
这是最简单的方法。使用简单变量和import设置文件。
调用文件 userprefs.py
# a user prefs file
color = 0x010203
font = "times new roman"
position = ( 12, 13 )
size = ( 640, 480 )
Run Code Online (Sandbox Code Playgroud)
在您的应用程序中,您需要确保可以导入此文件。你有很多选择。
使用PYTHONPATH. 需要PYTHONPATH设置为包含首选项文件的目录。
一种。用于命名文件的显式命令行参数(不是最好的,但很简单)
湾 用于命名文件的环境变量。
扩展sys.path以包含用户的主目录
例子
import sys
import os
sys.path.insert(0,os.path.expanduser("~"))
import userprefs
print userprefs.color
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9057 次 |
| 最近记录: |