在python中读取属性文件的快速方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3997777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:46:37  来源:igfitidea点击:

what would be a quick way to read a property file in python?

pythonconfiguration-files

提问by jury

I have a file with the format

我有一个格式的文件

VarName=Value
.
.

I want to read it into a hash such that H("VarName")will return the value.

我想将它读入一个哈希值,以便H("VarName")返回值。

What would be a quick way? (read a set of strings, split all of them where the equality sign is, and then put it into a hash?

什么是快速的方法?(读取一组字符串,将它们全部拆分到等号所在的位置,然后将其放入散列中?

I am working with python.

我正在使用python。

回答by user470379

d = {}
with open('filename') as f:
    for line in f:
        key, value = line.split('=')
        d[key] = value

Edit: As suggested by foret, you could change it to

编辑:正如foret所建议的,您可以将其更改为

    for line in f:
        tokens = line.split('=')
        d[tokens[0]] = '='.join(tokens[1:])

which would handle the case where equals signs were allowed in the value, but would still fail if the name could have equals signs as well -- for that you would need a true parser.

这将处理值中允许使用等号的情况,但如果名称也可以包含等号,它仍然会失败——因为你需要一个真正的解析器。

回答by user151019

回答by rubik

Maybe ConfigParsercan help you.

也许ConfigParser可以帮助你。

回答by GreenMatt

The csv modulewill let you do this easily enough:

CSV模块可以让你做到这一点很容易不够:

import csv
H = dict([(row[0], row[1]) for row in csv.reader(open('the_file', 'r'), delimiter='=' )])

回答by Steven

The oneliner answer:

单线回答:

H = dict(line.strip().split('=') for line in open('filename.txt'))

(optionally use .split()with maxsplit=1if the values could also contain the "=" character)

(如果值也可以包含“=”字符.split()maxsplit=1则可以选择使用)

回答by mouad

this may be a stupid answer but who know maybe it can help you :)

这可能是一个愚蠢的答案,但谁知道它可以帮助你:)

change the extension of your file to .py, and do necessary change like this:

将文件的扩展名更改为 .py,并进行如下必要的更改:

file.py

文件.py

VarName="Value"   # if it's a string
VarName_2=1
# and you can also assign a dict a list to a var, how cool is that ?

and put it in your package tree or in sys.path, and now you can call it like this in the script when you want to use it:

并将其放入您的包树或 sys.path 中,现在您可以在要使用它时在脚本中这样调用它:

>>> import file
>>> file.VarName
'Value'

why i'm writing this answer it's because ,what the hell is this file ? i never see a conf file like this , no section no nothing ? why you want to create a config file like this ? it look like a bad config file that should look like the Django settings, and i prefer using a django setting-like config file when ever i can.

为什么我写这个答案是因为,这个文件到底是什么?我从来没有看到过这样的 conf 文件,没有部分没有什么?为什么要创建这样的配置文件?它看起来像一个糟糕的配置文件,应该看起来像 Django 设置,我更喜欢尽可能使用类似 django 设置的配置文件。

Now you can put your -1 in the left :)

现在你可以把你的 -1 放在左边:)

回答by GBF_Gabriel

Taking @Steven's answer doesn't account comments and newlines in the properties file, this one does:

以@Steven 的回答不考虑属性文件中的注释和换行符,这个是:

H = dict(line.strip().split('=') for line in open('file.properties') if not line.startswith('#') and not line.startswith('\n'))  

回答by TheCuriousOne

If you need to read all values from a section in properties file in a simple manner:

如果您需要以简单的方式从属性文件中的某个部分读取所有值:

Your config.properties file layout :

您的 config.properties 文件布局:

[SECTION_NAME]  
key1 = value1  
key2 = value2  

You code:

你编码:

import configparser

config = configparser.RawConfigParser()
config.read('path_to_config.properties file')

details_dict = dict(config.items('SECTION_NAME'))

This will give you a dictionary where keys are same as in config file and their corresponding values.

这将为您提供一个字典,其中的键与配置文件中的键及其对应的值相同。

details_dict becomes

{'key1':'value1', 'key2':'value2'}

Now to get key1's value :

现在获取 key1 的值:

value_1 = details_dict['key1']

Putting it all in a method which reads that section from config file only once(the first time the method is called during a program run).

将所有内容放在一个方法中,该方法仅从配置文件中读取该部分一次(在程序运行期间第一次调用该方法)。

def get_config_dict():
    if not hasattr(get_config_dict, 'config_dict'):
        get_config_dict.config_dict = dict(config.items('SECTION_NAME'))
    return get_config_dict.config_dict

Now call the above function and get the required key's value :

现在调用上面的函数并获取所需的键值:

config_details = get_config_dict()
key_1_value = config_details['key1'] 

回答by Igor A

For python2 there is a jproperties https://pypi.python.org/pypi/jproperties/1.0.1

对于 python2,有一个 jproperties https://pypi.python.org/pypi/jproperties/1.0.1

For python2/3 there is javaproperties http://javaproperties.readthedocs.io/en/v0.1.0/

对于 python2/3,有 javaproperties http://javaproperties.readthedocs.io/en/v0.1.0/

as simple as:

就像这样简单:

import os, javaproperties
with open(file, 'rb') as f:
    properties_dict = javaproperties.load(f)

回答by searchengine27

OK nobody else in the answers has mentioned it, so I guess I'm going to. If you're writing Python, and have control over your interpreter, maybe you can force the use of the Jythoninterpreter.

好吧,答案中没有其他人提到过它,所以我想我要去。如果您正在编写 Python,并且可以控制您的解释器,也许您可​​以强制使用Jython解释器。

Jythonis a Python interpreter implemented entirely in Java. You have all the Python standard libraries at your fingertips, with the additional advantage of all your Java SE libraries available.

Jython是一个完全用 Java 实现的 Python 解释器。所有 Python 标准库都触手可及,还有所有可用 Java SE 库的额外优势。

I haven't actually executed any of the following (think of it more like psudeo-code without exception handling), but you can mix and match Python and Java libraries, and your code might end up looking something like:

我实际上并没有执行以下任何操作(把它想象成没有异常处理的伪代码),但是你可以混合和匹配 Python 和 Java 库,你的代码最终可能看起来像这样:

from java.util import Properties
from java.io import File, FileInputStream
import os
javasPropertyObject = Properties()
pathToPropFile = os.path.join('path', 'to', 'property', 'file.properties')
if os.path.isfile(pathToPropFile):
    #this is java.io.File, not Python's file descriptor
    propFile = File(pathToPropFile )
    javasFileInputStreamObject = FileInputStream(propFile)
    javasPropertyObject.load(javasFileInputStreamObject)

    #now we can pull out Java properties as defined by the .property file grammar
    myProp = javasPropertyObject.getProperty('myPropName')

where a file like this will be valid, that wouldn't in the simple split on '='solutions:

在这样的文件将有效的情况下,在简单的split on '='解决方案中不会:

myPropName1:value
myPropName2=value
myPropName3=\
value
#this is a = comment
myPropName4:my \
value
myPropNameWithUnicode=\u0009

The downside, is that you lose your ability to be portable among varying Python interpreters and now you're locked into Jython. You would be locked into a library if you attempt that approach as well. The reason why I like Jython is that your added flexibility with having all of the Java SE libraries available.

不利的一面是,您失去了在不同 Python 解释器之间移植的能力,现在您被锁定在 Jython 中。如果你也尝试这种方法,你会被锁在图书馆里。我喜欢 Jython 的原因是您拥有所有可用的 Java SE 库,从而增加了灵活性。