首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

关于python的一个字典的有关问题

2012-03-21 
关于python的一个字典的问题下面是一段Python的代码Python code#-*- coding:utf-8 -*-scope{}def getsett

关于python的一个字典的问题
下面是一段Python的代码

 

Python code
#-*- coding:utf-8 -*-  scope={}def getsetting(filepath):      f = open(filepath)      for l in f:          scope[l.split('=')[0].strip()]=l.split('=')[1][:-1].strip()          print scope[l.split('=')[0].strip()]      f.close()      print scope['case_no']    if __name__ == '__main__':      getsetting('setting1.ini')  

下面是setting1.ini的文件内容:
case_no = case_no
consignor = consignor
contact = contact
contact_address =contact_address
contact_number = contact_number
delegate_date = delegate_date
case_brief =case_brief 
delegate_info = delegate_info
identification_demand = identification_demand
identification_materials = identification_materials
identification_samples = identification_samples
 
为什么每次都报
 
Traceback (most recent call last):
  File "E:\WorkSpace\Python\template\createfile.py", line 28, in <module>
  getsetting('setting1.ini')
  File "E:\WorkSpace\Python\template\createfile.py", line 16, in getsetting
  print scope['case_no']
KeyError: 'case_no'
的错误。
而其它的键值都没有问题,就只有这个case_no了,改了其它名称也不行。

[解决办法]
代码最好不要有文件读写,重现起来麻烦。下面的代码执行无异常:

Python code
x = '''case_no = case_noconsignor = consignorcontact = contactcontact_address =contact_addresscontact_number = contact_numberdelegate_date = delegate_datecase_brief =case_brief delegate_info = delegate_infoidentification_demand = identification_demandidentification_materials = identification_materialsidentification_samples = identification_samples'''scope={}def getsetting():      for l in x.splitlines():        scope[l.split('=')[0].strip()]=l.split('=')[1][:-1].strip()          print scope[l.split('=')[0].strip()]      print scope['case_no']    if __name__ == '__main__':      getsetting()
[解决办法]
没有就应该是没有,你print scope看看整个字典先,可能你的ini文件有bom头,简单open()并不会滤掉...

热点排行