按照老師寫的代碼,自己run報錯NoSectionError: No section: 'user',請教怎么解決
報錯信息如下:
=================== RESTART: C:/Python27/0506/文件練習.py ===================
-------------->
-------------->
Traceback (most recent call last):
? File "C:/Python27/0506/文件練習.py", line 43, in <module>
? ? info.set_item('userinfo','pwd','abc')
? File "C:/Python27/0506/文件練習.py", line 32, in set_item
? ? self.cfg.set(section,key,value)
? File "C:\Python27\lib\ConfigParser.py", line 396, in set
? ? raise NoSectionError(section)
NoSectionError: No section: 'userinfo'
imooc.txt內容如下:
[userinfo]
name=zhangsan
pwd=abc
[study]
python_bse=15
python_junior=20
linux_base =15
代碼如下
import os
import os.path
import ConfigParser
class student_info(object):
? ? def __init__(self,recordfile):
? ? ? ? self.logfile = recordfile
? ? ? ? self.cfg = ConfigParser.ConfigParser()
? ? def cfg_load(self):
? ? ? ? self.cfg.read(self.logfile)
? ? def cfg_dump(self):
? ? ? ? se_list = self.cfg.sections()
? ? ? ? print"-------------->"
? ? ? ? for se in se_list:
? ? ? ? ? ? print se
? ? ? ? ? ? print se_list.items(se)
? ? ? ? print"-------------->"
? ? def delete_item(self,section,key):
? ? ? ? self.cfg.remove_option(section,key)
? ? def delete_section(self,section):
? ? ? ? self.cfg.remove_section(section)
? ? def add_section(self,section):
? ? ? ? secl.cfg.add_section(section)
? ? def set_item(self,section,key,value):
? ? ? ? self.cfg.set(section,key,value)
? ? def save(self):
? ? ? ? fp = open(self.logfile,'w')
? ? ? ? self.cfg.write(fp)
? ? ? ? fp.close()
if __name__ == '__main__':
? ? info = student_info('imooc.txt')
? ? info.cfg_load()
? ? info.cfg_dump()
? ? info.set_item('userinfo','pwd','abc')
? ? info.cfg_dump()
? ? info.add_section('login')
? ? info.set_item('login','2015-05-11','20')
? ? info.cfg_dum()
? ? info.save()
txt文件里明明有userinfo,求解。
2019-06-12
可能是文件沒有讀取到
2019-09-06
怎么解決的吶?我的是輸出[],搞不明白為什么!