博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python文件练习
阅读量:7212 次
发布时间:2019-06-29

本文共 1748 字,大约阅读时间需要 5 分钟。

练习内容:

      使用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()

  

 

转载于:https://www.cnblogs.com/Nyan-Workflow-FC/p/5657253.html

你可能感兴趣的文章
Leetcode | Balanced Binary Tree
查看>>
sqlServer对内存的管理
查看>>
挑战密室
查看>>
利用Solr服务建立的站内搜索雏形---solr1
查看>>
5、jmeter-逻辑控制器介绍与使用
查看>>
如何遍历List对象
查看>>
2012年4月19日
查看>>
获取站点所有缓存,以及清除站点缓存
查看>>
oracle 是user_tables里面可以查找到一个表,而用DESC或者insert语句插入时就会报不存在视图。...
查看>>
找水王续
查看>>
cocos2d-x之Node移除HelloWorld节点
查看>>
AtCoder WTF 2019 C2. Triangular Lamps Hard
查看>>
[转].NET Framework、C#、CLR和Visual Studo之间的版本关系
查看>>
sql语句-2-字符串数字日期时间
查看>>
[Python3网络爬虫开发实战] 3.1.2-处理异常
查看>>
25、没有编程基础可以学习PHP吗?
查看>>
mybatis案例源码详解
查看>>
Python--day37--进程锁
查看>>
导出PDF乱码
查看>>
UE4的AI学习(1)——基本概念
查看>>