Python ConfigParser问题 [英] Python ConfigParser Question

查看:122
本文介绍了Python ConfigParser问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否必须将ConfigParser的Config文件命名为"Config.ini"才能正常工作?

Does the Config file for the ConfigParser have to be named "Config.ini" in order to work?

我希望名称为"1Config.ini",以便它出现在文件夹目录的顶部.

I want the name to be "1Config.ini" so that it appears at the top of a folder dir.

这是我目前拥有的

config = ConfigParser.ConfigParser()
config.read(Revision[0:Revision.rfind('\\')] + "\1Config.ini")

Type = config.get("myvars", "Type")

但是当文件和代码命名为"1Config.ini"时出现此错误

I get this error however when the file and code is named "1Config.ini"

<class 'ConfigParser.NoSectionError'>: No section: 'myvars'

推荐答案

以下内容的输出是什么?确保它是有效的文件名.

What's the output of the following? Make sure it's a valid file name.

>>> print Revision[0:Revision.rfind('\\')] + "\1Config.ini"

理想情况下,使用os.path.join代替串联字符串:

Ideally use os.path.join instead of concatenating strings:

import os
filename = os.path.join(Revision[0:Revision.rfind('\\')], "Config.ini")
config.read(filename)

您可能不应该将变量命名为Type,因为type是内置函数/模块,会造成混淆.

You probably shouldn't name your variable Type, because type is a built-in function/module and it'd be confusing.

Type = config.get("myvars", "Type")

不,配置文件可以命名为任何东西

And no, config files can be named anything:

>>> a = ConfigParser.ConfigParser()
>>> a.read("E:/Documents/2012/config.test") # where config.test is the example from the documentation
['E:/Documents/2012/config.test']
>>> a.sections()
['My Section']
>>> a.items(a.sections()[0])
[('foodir', 'frob/whatever'),
 ('dir', 'frob'),
 ('long', 'this value continues\nin the next line')]

这篇关于Python ConfigParser问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆