Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用python读取配置文件_Python - Fatal编程技术网

如何使用python读取配置文件

如何使用python读取配置文件,python,Python,我有一个配置文件abc.txt,看起来有点像: path1 = "D:\test1\first" path2 = "D:\test2\second" path3 = "D:\test2\third" 我想从abc.txt中读取这些路径,以便在我的程序中使用它以避免硬编码。这看起来像是有效的Python代码,因此如果文件位于项目的类路径上(而不是在其他目录或任意位置),一种方法就是将文件重命名为“abc.py”,并将其作为模块导入,使用导入abc。您甚至可以在以后使用reload功能更新这些值。

我有一个配置文件
abc.txt
,看起来有点像:

path1 = "D:\test1\first"
path2 = "D:\test2\second"
path3 = "D:\test2\third"

我想从
abc.txt
中读取这些路径,以便在我的程序中使用它以避免硬编码。

这看起来像是有效的Python代码,因此如果文件位于项目的类路径上(而不是在其他目录或任意位置),一种方法就是将文件重命名为“abc.py”,并将其作为模块导入,使用
导入abc
。您甚至可以在以后使用
reload
功能更新这些值。然后访问值,如
abc.path1

当然,如果文件包含将要执行的其他代码,这可能会很危险。我不会在任何真正的专业项目中使用它,但对于小脚本或交互模式,这似乎是最简单的解决方案


只需将
abc.py
放在与脚本相同的目录中,或者放在打开交互式shell的目录中,然后从abc import*导入abc或
,为了使用我的示例,您的文件“abc.txt”需要如下所示:

[your-config]
path1 = "D:\test1\first"
path2 = "D:\test2\second"
path3 = "D:\test2\third"
然后,您可以在软件中使用配置解析器:

import ConfigParser
然后在代码中:

 configParser = ConfigParser.RawConfigParser()   
 configFilePath = r'c:\abc.txt'
 configParser.read(configFilePath)
用例:

self.path = configParser.get('your-config', 'path1')
*编辑(@human.js)


在Python 3中,ConfigParser重命名为ConfigParser()

文件中需要一个部分:

[My Section]
path1 = D:\test1\first
path2 = D:\test2\second
path3 = D:\test2\third
然后,阅读属性:

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')

由于您的配置文件是一个普通文本文件,因此只需使用
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]
这将打印您的路径。您还可以使用字典列表存储它们

path_list = []
path_dict = {}
for path in paths:
    p = path.split(" = ")
    path_list.append(p)[1]
    path_dict[p[0]] = p[1]
有关读取/写入文件的更多信息。
希望这有帮助

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

您的
config.cfg
文件布局:

[SECTION_NAME]  
key1 = value1  
key2 = value2  
您的代码是:

   import configparser

   config = configparser.RawConfigParser()
   config.read('path_to_config.cfg file')
    
   details_dict = dict(config.items('SECTION_NAME'))
这将为您提供一个字典,其中键与配置文件中的键及其对应值相同

详细信息\u dict
是:

{'key1':'value1', 'key2':'value2'}
现在要获取key1的值:
details\u dict['key1']

将其全部放在一个只从配置文件读取一次节的方法中(在程序运行期间第一次调用该方法)。

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
现在调用上述函数并获取所需的键值:

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


通用多段法:

config_dict = get_config_section()

port = config_dict['DB']['port'] 
扩展上述方法,自动逐节读取,然后按节名和键名访问

def get_config_section():
    if not hasattr(get_config_section, 'section_dict'):
        get_config_section.section_dict = collections.defaultdict()
        
        for section in config.sections():
            get_config_section.section_dict[section] = dict(config.items(section))
    
    return get_config_section.section_dict
访问:

config_dict = get_config_section()

port = config_dict['DB']['port'] 
(这里,'DB'是配置文件中的节名
'port'是“DB”部分下的一个键。

在您的情况下,一个方便的解决方案是将配置包含在名为
**your_config_name.yml**
如下所示:

path1: "D:\test1\first"
path2: "D:\test2\second"
path3: "D:\test2\third"
在python代码中,您可以通过以下操作将配置参数加载到字典中:

import yaml
with open('your_config_name.yml') as stream:
    config = yaml.safe_load(stream)
然后,您可以通过字典配置访问路径1,如下所示:


要导入yaml,您首先必须将软件包安装为:
pip install pyyaml
到您选择的虚拟环境中。

我编辑了这篇文章,我的建议是使用配置文件,这样做更简单、更有用,这样您就可以学到一个真正能帮助您的新东西。错误
丢失节头错误
是因为您需要节
[文件]
肯定有用;我以前不知道+1@KobiK我能够通过os.path.abspath(os.path.dirname(sys.argv[0])获得当前执行的脚本文件的路径。然后我可以用我的“abc.txt”做一个os.path.join。这就解决了问题。多亏了python 3,ConfigParser被重命名为ConfigParser。查看此处了解详细信息。由于使用configParser,您可能希望从配置文件变量内容中删除引号。get('your-config','path1')将添加另一组(单个)引号(在python3 configParser上测试)。请记住
关闭
文件,或者更好地使用
with
块。还有,如果它只是一个文本文件,我建议放弃引号。@tobias_k他可以自己弄清楚:)谢谢,但我没有项目构建和所有内容。我只是从命令行运行Python脚本。在这种情况下有可能这样做吗?我的意思是,有没有其他方法将它们作为一个包或类似的东西放在一起?@user2882117当然,只需将
abc.py
放在与脚本相同的目录中,或者放在启动交互式shell的目录中,然后导入abc
。特别是如果只是一个小脚本,我认为这是最简单的解决方案,但我不会在“真正”的项目中使用它。你需要小心字符串中的反斜杠。发明自己的格式,即使它们看起来很简单,通常也不是最好的主意。最好坚持使用内置的,有很多选择:.ini、json、yaml、xml…相关:另请参见readfp已弃用。改为使用read\u文件:
config.read\u文件(open(r'abc.txt'))
您甚至可以使用
config.read(r'abc.txt')
。见官方死亡报告。
config['path1']