Python ConfigParser.NoSectionError:无节:

2024-04-20 06:39:47 发布

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

我一直在获取ConfigParser.No section error:没有节:'file'错误

我的配置文件如下:

[file]
api_access_id = 123445567
api_default_org = NAME
api_secret_key = kjvhkd28unfkjs
api_base_url = www.fakeurl.com/api

我的代码看起来像:

config = ConfigParser.RawConfigParser()
configFilePath = 'E:\Python\configfile\test.txt'
config.read(configFilePath)

try:
    api_access_id = config.get('file', 'api_access_id')
    api_secret_key = config.get('file', 'api_secret_key')
    api_default_org = config.get('file', 'api_default_org')
    api_base_url = config.get('file', 'api_base_url')
except ConfigParser.NoOptionError :
    print('could not read configuration file')
    sys.exit(1)  

错误是:

Traceback (most recent call last):
File "E:/Python/Testapi.py", line 13, in <module>
api_access_id = config.get('file', 'api_access_id')
File "C:\Python27\lib\ConfigParser.py", line 330, in get
raise NoSectionError(section)
ConfigParser.NoSectionError: No section: 'file'

Process finished with exit code 1

有人知道是什么导致了这个问题吗?


Tags: keynoorgapiidconfigdefaulturl
3条回答

由于路径长度(>;256),我出现此错误

它是通过给出绝对路径来解决的

 import os
 thisfolder = os.path.dirname(os.path.abspath(__file__))
 initfile = os.path.join(thisfolder, 'you_file_name.init')
 # print thisfolder

 config = RawConfigParser()
 res = config.read(initfile)

 data = config.get('section_name', 'variable_name')

已将文件url更改为

 configFilePath = 'test.txt'

因为我的文件已经在我的应用程序文件夹中

你用反斜杠定义你的路径:

configFilePath = 'E:\Python\configfile\test.txt'

这些将被解释为转义,因此不会加载正确的文件。(不幸的是,错误消息在这种情况下没有多大帮助。)您要么需要转义它们,要么使用原始字符串:

configFilePath = r'E:\Python\configfile\test.txt'

相关问题 更多 >