Python文件练习,,练习内容: 使用


练习内容:

使用Python管理ini文件:实现查询,添加,删除,保存操作。

练习目的:

1.掌握文件基本操作

  2.认识ini文件

  3.了解ConfigParser;

ini配置文件格式:

节:[session]

参数(键=值)

[port]

  port1=3306

import ConfigParser

cfg=ConfigParser.ConfigParser()

vim test.txt

[userinfo]

name=nyan

pwd=password

[study]

python_base=15

python_junior=30

linux_base=15


cfg.read(‘test.txt‘)

cfg.sections()

cfg.items

for se in cfg.sections():

  print se

  print cfg.items(se)

cfg.set(‘userinfo‘,‘pwd‘,‘passw0rd‘):修改

cfg.set(‘userinfo‘,‘email‘,‘sibaoemail@qq.com‘):插入

cfg.remove_option(‘userinfo‘,‘email‘)

inimanage.py

import os

import os.path

import ConfugParser

...

1.dump ini

2.del section

3.del item

4.modify item

5.add section

6.save modify

...

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 self.cfg.items(se)

    print "================="

  def delete_item(self,section,key):

    self.cfg.remove_option(setion,key)

  def delete_section(self , section):

    self.cfg.remove_section(section)

  def add_section(self,section):

    self.cfg.add_section(section)

  def set_item(self,section,key,value):

    self.cfg.set(section,key,value)

  def save(self):

    fp = oopen(‘test.txt‘,‘w‘)

    self.cfg.write(fp)

    dp.close()

if __name__ == ‘__main__‘:

  info = student_info(‘test.txt‘)

  info.cfg_load()

  info.cfg_dump()

  info.set_item(‘userinfo‘,‘pwd‘,‘passw0rd‘)

  info.cfg_dump()

  info.add_section(‘login‘)

  info.set_item(‘login‘,‘2015-0511‘,‘20‘)

  info.cfg_dump()

  info.save()

  

Python文件练习

相关内容

    暂无相关文章

评论关闭