如何在python中读取属性文件

2024-05-02 17:47:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份财产档案

Configuration.properties
path=/usr/bin
db=mysql
data_path=/temp

我需要读取这个文件,并在随后的脚本中使用诸如path、db和data_path之类的变量。 我可以使用configParser来完成这项工作,也可以简单地读取文件并获取值。 提前谢谢。


Tags: 文件path脚本dbdatabinusrmysql
3条回答

我喜欢现在的答案。还有。。。我觉得在“现实世界”里有一种更干净的方式来做这件事。如果要执行任何大小或规模的项目,尤其是在“多个”环境中,则必须使用节头功能。我想把它与格式良好的可复制代码放在这里,使用一个健壮的现实世界的例子。这是在Ubuntu 14中运行的,但是可以跨平台工作:

现实世界的简单例子

基于环境的配置
设置示例(终端):

cd ~/my/cool/project touch local.properties touch environ.properties ls -la ~/my/cool/project -rwx------ 1 www-data www-data 0 Jan 24 23:37 local.properties -rwx------ 1 www-data www-data 0 Jan 24 23:37 environ.properties

设置好权限

>> chmod 644 local.properties
>> chmod 644 env.properties
>> ls -la
-rwxr--r-- 1 www-data www-data  0 Jan 24 23:37 local.properties
-rwxr--r-- 1 www-data www-data  0 Jan 24 23:37 environ.properties

编辑属性文件。

文件1:local.properties

这是您的属性文件,位于您的计算机和工作区的本地,包含敏感数据,不要推送到版本控制!!!

[global]
relPath=local/path/to/images              
filefilters=(.jpg)|(.png)

[dev.mysql]
dbPwd=localpwd
dbUser=localrootuser

[prod.mysql]
dbPwd=5tR0ngpwD!@#
dbUser=serverRootUser

[branch]
# change this to point the script at a specific environment
env=dev

文件2:环境属性

此属性文件由所有人共享,更改将推送到版本控制

#----------------------------------------------------
# Dev Environment
#----------------------------------------------------

[dev.mysql]
dbUrl=localhost
dbName=db

[dev.ftp]
site=localhost
uploaddir=http://localhost/www/public/images

[dev.cdn]
url=http://localhost/cdn/www/images


#----------------------------------------------------
# Prod Environment
#----------------------------------------------------
[prod.mysql]
dbUrl=http://yoursite.com:80
dbName=db

[prod.ftp]
site=ftp.yoursite.com:22
uploaddir=/www/public/

[prod.cdn]
url=http://s3.amazon.com/your/images/

Python文件:readCfg.py

此脚本是一个可重用的片段,用于加载配置文件列表 导入配置分析器 导入操作系统

# a simple function to read an array of configuration files into a config object
def read_config(cfg_files):
    if(cfg_files != None):
        config = ConfigParser.RawConfigParser()

        # merges all files into a single config
        for i, cfg_file in enumerate(cfg_files):
            if(os.path.exists(cfg_file)):
                config.read(cfg_file)

        return config

Python文件:yourCoolProgram.py

此程序将导入上面的文件,并调用“read_config”方法

from readCfg import read_config

#merge all into one config dictionary
config      = read_config(['local.properties', 'environ.properties'])

if(config == None):
    return

# get the current branch (from local.properties)
env      = config.get('branch','env')        

# proceed to point everything at the 'branched' resources
dbUrl       = config.get(env+'.mysql','dbUrl')
dbUser      = config.get(env+'.mysql','dbUser')
dbPwd       = config.get(env+'.mysql','dbPwd')
dbName      = config.get(env+'.mysql','dbName')

# global values
relPath = config.get('global','relPath')
filefilterList = config.get('global','filefilters').split('|')

print "files are: ", fileFilterList, "relative dir is: ", relPath
print "branch is: ", env, " sensitive data: ", dbUser, dbPwd

结论

根据上述配置,现在可以有一个脚本,通过更改“local.properties”中的[branch]env值来完全更改环境。这都是基于良好的配置原则!耶!

是的,你可以。

ConfigParser(https://docs.python.org/2/library/configparser.html)将为您提供一个很好的小结构来从开箱即用中获取值,手工操作需要一些字符串拆分,但是对于一个简单的格式文件来说,这没什么大不了的。

问题是“如何读取此文件?”。

对于没有节头、被[]包围的配置文件,将引发ConfigParser.NoSectionError异常。可以通过插入“假”节头来解决此问题,如this answer中所示。

如果文件很简单,如pcalcao's answer所述,您可以执行一些字符串操作来提取值。

下面是一个代码片段,它返回配置文件中每个元素的键值对字典。

separator = "="
keys = {}

# I named your file conf and stored it 
# in the same directory as the script

with open('conf') as f:

    for line in f:
        if separator in line:

            # Find the name and value by splitting the string
            name, value = line.split(separator, 1)

            # Assign key value pair to dict
            # strip() removes white space from the ends of strings
            keys[name.strip()] = value.strip()

print(keys)

相关问题 更多 >