如何使用python读取配置文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19379120/
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
How to read a config file using python
提问by a4aravind
I have a config file abc.txt
which looks somewhat like:
我有一个abc.txt
看起来有点像的配置文件:
path1 = "D:\test1\first"
path2 = "D:\test2\second"
path3 = "D:\test2\third"
I want to read these paths from the abc.txt
to use it in my program to avoid hard coding.
我想从 中读取这些路径abc.txt
以在我的程序中使用它以避免硬编码。
采纳答案by Kobi K
In order to use my example,Your file "abc.txt" needs to look like:
为了使用我的示例,您的文件“abc.txt”需要如下所示:
[your-config]
path1 = "D:\test1\first"
path2 = "D:\test2\second"
path3 = "D:\test2\third"
Then in your software you can use the config parser:
然后在您的软件中,您可以使用配置解析器:
import ConfigParser
and then in you code:
然后在你的代码中:
configParser = ConfigParser.RawConfigParser()
configFilePath = r'c:\abc.txt'
configParser.read(configFilePath)
Use case:
用例:
self.path = configParser.get('your-config', 'path1')
*Edit (@human.js)
*编辑(@human.js)
in python 3, ConfigParser is renamed to configparser (as described here)
在 python 3 中,ConfigParser 被重命名为 configparser(如此处所述)
回答by tobias_k
This looks like valid Python code, so if the file is on your project's classpath (and not in some other directory or in arbitrary places) one way would be just to rename the file to "abc.py" and import it as a module, using import abc
. You can even update the values using the reload
function later. Then access the values as abc.path1
etc.
这看起来像有效的 Python 代码,所以如果文件在您项目的类路径上(而不是在其他目录或任意位置),一种方法就是将文件重命名为“abc.py”并将其作为模块导入,使用import abc
. 您甚至可以reload
稍后使用该函数更新值。然后访问值abc.path1
等。
Of course, this canbe dangerous in case the file contains other code that will be executed. I would not use it in any real, professional project, but for a small script or in interactive mode this seems to be the simplest solution.
当然,如果文件包含将要执行的其他代码,这可能很危险。我不会在任何真正的专业项目中使用它,但对于小脚本或交互模式,这似乎是最简单的解决方案。
Just put the abc.py
into the same directory as your script, or the directory where you open the interactive shell, and do import abc
or from abc import *
.
只需将abc.py
放入与脚本相同的目录或打开交互式 shell 的目录中,然后执行import abc
或from abc import *
.
回答by user278064
You need a section in your file:
您的文件中需要一个部分:
[My Section]
path1 = D:\test1\first
path2 = D:\test2\second
path3 = D:\test2\third
Then, read the properties:
然后,读取属性:
import ConfigParser
config = ConfigParser.ConfigParser()
config.readfp(open(r'abc.txt'))
path1 = config.get('My Section', 'path1')
path2 = config.get('My Section', 'path2')
path3 = config.get('My Section', 'path3')
回答by aIKid
Since your config file is a normal text file, just read it using the open
function:
由于您的配置文件是一个普通的文本文件,只需使用以下open
函数读取它:
file = open("abc.txt", 'r')
content = file.read()
paths = content.split("\n") #split it into lines
for path in paths:
print path.split(" = ")[1]
This will print your paths. You can also store them using dictionaries orlists.
这将打印您的路径。您还可以使用字典或列表来存储它们。
path_list = []
path_dict = {}
for path in paths:
p = path.split(" = ")
path_list.append(p)[1]
path_dict[p[0]] = p[1]
More on reading/writing file here. Hope this helps!
更多关于读/写文件在这里。希望这可以帮助!
回答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
is :
details_dict
是 :
{'key1':'value1', 'key2':'value2'}
Now to get key1's value :
details_dict['key1']
现在获取 key1 的值:
details_dict['key1']
Putting it all in a method which reads sections 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']
-------------------------------------------------------------
-------------------------------------------------- -----------
Extending the approach mentioned above, reading section by section automatically and then accessing by section name followed by key name.
扩展上述方法,自动逐节读取,然后按节名和键名访问。
def get_config_section():
if not hasattr(get_config_section, 'section_dict'):
get_config_section.section_dict = dict()
for section in config.sections():
get_config_section.section_dict[section] = dict(config.items(section))
return get_config_section.section_dict
def get_config_section():
if not hasattr(get_config_section, 'section_dict'):
get_config_section.section_dict = dict()
for section in config.sections():
get_config_section.section_dict[section] = dict(config.items(section))
return get_config_section.section_dict
To access:
访问:
config_dict = get_config_section()
port = config_dict['DB']['port']
(here 'DB' is a section name in config file and 'port' is a key under section 'DB'.)
(这里'DB'是配置文件中的一个部分名称,'port'是'DB'部分下的一个键。)