Python-引发KeyError(key),但不应这样做

时间:2018-06-19 12:42:28

标签: python-3.x configparser

为什么此代码引发错误:

import configparser
import os


path = '/home/solus/Downloads/TestOnMe'
os.chdir(path)

config = configparser.ConfigParser()

config.read('extensions.ini')
extensions = config['Extensions']

但是相反,这段代码可以完美地工作:

import configparser
import os


config = configparser.ConfigParser()

config.read('extensions.ini')
extensions = config['Extensions']

错误如下:

Traceback (most recent call last):
  File "/home/solus/Documents/Projects/Python/Learning Python from YT/Own/configurator/testtesttest.py", line 11, in <module>
    extensions = config['Extensions']
  File "/usr/lib/python3.6/configparser.py", line 959, in __getitem__
    raise KeyError(key)
KeyError: 'Extensions'

extensions.ini的内容:

[Extensions]
music = ['mp3', 'acc']
photos = ['jpeg', 'jpg', 'png']
archives = ['rar', 'zip', 'tar', 'tar.bz', 'tar.gz']
documents = ['epub', 'pdf', 'doc']

Python文件和.ini文件都在同一目录中。

1 个答案:

答案 0 :(得分:0)

答案很简单。仔细观察:

import configparser
import os


path = '/home/solus/Downloads/TestOnMe'
os.chdir(path)

使用os.chdir(path),您将路径更改为'/home/solus/Downloads/TestOnMe'。由于路径已更改,Python会尝试在 TestOnMe 目录中搜索extensions.ini。那就是为什么会引发错误。要更正此错误,您需要更改说明的顺序。

import configparser
import os


config = configparser.ConfigParser()
config.read('extensions.ini')

path = '/home/solus/Downloads/TestOnMe'
os.chdir(path)

extensions = config['Extensions']