Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.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_Import_Module_Python 3.x_Configparser - Fatal编程技术网

Python 如何从模块和主文件中读取配置文件?

Python 如何从模块和主文件中读取配置文件?,python,import,module,python-3.x,configparser,Python,Import,Module,Python 3.x,Configparser,我在加载和读取配置文件时遇到问题。当我运行imptest.py文件时,Python读取configfile.cfg并得到以下输出: D:\tmp\test\dir1>python imptest.py Section1 Section2 Section3 但是当我运行mainfile.py文件时,没有发生任何事情,Python似乎没有读取configfile.cfg文件: D:\tmp\test>python mainfile.py D:\tmp\test> 我的目录结构

我在加载和读取配置文件时遇到问题。当我运行
imptest.py
文件时,Python读取
configfile.cfg
并得到以下输出:

D:\tmp\test\dir1>python imptest.py
Section1
Section2
Section3
但是当我运行
mainfile.py
文件时,没有发生任何事情,Python似乎没有读取
configfile.cfg
文件:

D:\tmp\test>python mainfile.py

D:\tmp\test>
我的目录结构:

test/ dir1/ __init__.py imptest.py static/ configfile.cfg mainfile.py
imptest.py
文件的来源:

D:\tmp\test>python mainfile.py

D:\tmp\test>
导入配置解析器
def run():
config=configparser.configparser()
config.read('../static/configfile.cfg',encoding='utf8')
对于config.sections()中的节:
印刷品(章节)
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
运行()
configfile.cfg
文件的来源:

D:\tmp\test>python mainfile.py

D:\tmp\test>
[第1节]
Foo=bar
端口=8081
[第2节]
Bar=foo
端口=8080
[第3节]
测试=123
端口=80
已编辑

到目前为止,我的解决方案(绝对路径)是:


它是更好、更差还是与@Yavar的解决方案相同?

如果您想要一个到
imptest.py
的相对路径,请使用
\uu文件\uuu

mydir = os.path.dirname(os.path.abspath(__file__))
new_path = os.path.join(mydir, '..', rest_of_the_path)
此外,请参见此问题的答案:

它找不到配置文件,因为从主文件版本调用时没有使用正确的路径

有趣的是,configparser会自动忽略。看看这个:

Python 3.2.3 (default, Sep 10 2012, 18:14:40) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import configparser
>>> 
>>> config = configparser.ConfigParser()
>>> config.read('doesnotexist.cfg')
[]
>>> print(config.sections())
[]
>>> 

谢谢!这是有效的,但我不知道我的解决方案是更好,更糟还是和你的一样?在我看来差不多。我唯一要注意的是,
os.path.join
负责连接多个路径组件,因此您实际上不需要
os.path.sep
。您的解决方案似乎更好。我对它进行了测试,效果非常好,完全符合我的预期。非常感谢你的帮助+1给你!:-)