如何使用python读取配置文件

2024-03-29 14:28:52 发布

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

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

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

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


Tags: 路径程序txt编码配置文件firstabcsecond
3条回答

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

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

只需将abc.py放入脚本所在的目录,或者打开交互式shell的目录,然后执行import abcfrom abc import *

为了使用我的示例,您的文件“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(as described here

您需要在文件中添加一个部分:

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

相关问题 更多 >