----------------------------接 python内置模块(二)---------------------------

八、 shelve模块

     shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式,他只有一个函数就是open(),这个函数接收一个参数就是文件名,然后返回一个shelf

对象,你可以用他来存储东西,就可以简单的把他当作一个字典,当你存储完毕的时候,就调用close

函数来关闭。

>>> import shelve

>>> sfile = shelve.open('shelve_test')    # 打开一个文件

>>> sfile['k1'] = []               # 持久化存储列表

>>> sfile['k1']

[]

>>> sfile.close()                  # 文件关闭

九、 xml处理模块

xml是实现不同语言或程序之间进行数据交换的协议,xml通过<>节点来区别数据结构的:

<?xml version="1.0"?>

<data>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

遍历xml文档

import xml.etree.ElementTree as ET

tree = ET.parse("test.xml")

root = tree.getroot()

print(root.tag)

#遍历xml文档

for child in root:

print(child.tag, child.attrib)

for i in child:

print(i.tag,i.text)

#只遍历year 节点

for node in root.iter('year'):

print(node.tag,node.text)

修改xml文档

import xml.etree.ElementTree as ET

tree = ET.parse("test.xml")

for node in root.iter('year'):

new_year = int(node.text) + 1

node.text = str(new_year)

node.set("updated","yes")

tree.write("test.xml")

for node in root.iter('year'):

print(node.tag,node.text)

删除xml内容

#删除node

import xml.etree.ElementTree as ET

tree = ET.parse("test.xml")

for country in root.findall('country'):

rank = int(country.find('rank').text)

if rank > 50:

root.remove(country)

tree.write('test.xml')

for child in root:

print(child.tag, child.attrib)

for i in child:

print(i.tag,i.text)

创建xml文档

import xml.etree.ElementTree as ET

new_xml = ET.Element("namelist")

name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})

age = ET.SubElement(name,"age",attrib={"checked":"no"})

sex = ET.SubElement(name,"sex")

age.text = '33'

sex.text = 'F'

name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})

age = ET.SubElement(name2,"age")

sex = ET.SubElement(name2,"sex")

age.text = '19'

sex.text = 'M'

et = ET.ElementTree(new_xml) #生成文档对象

et.write("test.xml", encoding="utf-8",xml_declaration=True)

ET.dump(new_xml) #打印生成的格式

        <namelist><name enrolled="yes"><age checked="no">33</age><sex>F</sex></name><name enrolled="no"><age>19</age><sex>M</sex></name></namelist>

十、 ConfigParser模块

用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。

常见软件配置文档格式如下:

[DEFAULT]

ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no

       生成配置文件方法:

import configparser

config = configparser.ConfigParser()

config["DEFAULT"] = {}

config["DEFAULT"]['ServerAliveInterval']=  '45'

config["DEFAULT"]['Compression'] = 'yes'

config["DEFAULT"]['CompressionLevel'] = '9'

config['DEFAULT']['ForwardX11'] = 'yes'

config['bitbucket.org'] = {}

config['bitbucket.org']['User'] = 'hg'

config['topsecret.server.com'] = {}

config['topsecret.server.com']['Host Port'] = '50022'

config['topsecret.server.com']['ForwardX11'] = 'no'

with open('example.ini', 'w') as configfile:

config.write(configfile)


   从配置文件中读出内容:

import configparser

config = configparser.ConfigParser()

print(config.sections())

print(config.read('example.ini'))  //想要读取配置文件中内容需要先执行此操作将内容读进内存;

print(config.sections())

print(config['bitbucket.org']['User'])

for key in config['DEFAULT']:

print(key)

结果是:

[]

['example.ini']

['bitbucket.org', 'topsecret.server.com']

hg

serveraliveinterval

compression

compressionlevel

forwardx11

      configparser增删改查语法

import configparser

config = configparser.ConfigParser()

config.read('example.ini')

# ********* 读 *********

#secs = config.sections()

#print(secs)

#options = config.options('bitbucket.org') // 获取sections下所有key值

#print(options)

#item_list = config.items('bitbucket.org') // 获取sections下所有items

#print(item_list)

#val = config.get('bitbucket.org','user')  // 在sections 下找到某key值

#val = config.getint('bitbucket.org','compressionlevel') // 先get 后int,即将int类型的

字符串转换成int类型

#print(val)

# ********** 改写 ***********

#sec = config.remove_section('bitbucket.org')

#config.write(open('new_example.ini', "w"))

#secs = config.has_section('bitbucket')

#config.add_section('bitbucket')

#config.write(open('example.cfg', "w"))

#config.set('bitbucket.org','user','shuoming')

#config.write(open('new_example.cfg', "w"))

#config.remove_option('bitbucket.org','user')

#config.write(open('new_example.cfg', "w"))


----------------------------接 内置模块(四)---------------------------

转载于:https://blog.51cto.com/51enjoy/1744068

python内置模块(三)相关推荐

  1. python内置模块_三分钟读懂Python内置模块collections

    collections模块 Python内置模块,在内置数据类型(dict.list.set.tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter.deque.d ...

  2. python turtle循环图案-Python内置模块turtle绘图详解

    urtle库是Python语言中一个很流行的绘制图像的函数库,想象一个小乌龟,在一个横轴为x.纵轴为y的坐标系原点,(0,0)位置开始,它根据一组函数指令的控制,在这个平面坐标系中移动,从而在它爬行的 ...

  3. python config模块_用Python内置模块处理ini配置文件

    原标题:用Python内置模块处理ini配置文件 简介 开发人员每天都在处理一些大型而复杂的项目, 而配置文件会帮到我们并节省不少时间.在处理配置文件过程中,无需更改源代码本身,只需要调整配置文件即可 ...

  4. Python中将三个列表数据zip起来并遍历(Iterating through three lists in parallel)

    Python中将三个列表数据zip起来并遍历(Iterating through three lists in parallel) 目录 Python中将三个列表数据zip起来并遍历(Iteratin ...

  5. python项目开发案例集锦 豆瓣-Python第三个项目:爬取豆瓣《哪吒之魔童降世》 短评...

    前面爬完网站信息图片之后,今天的又有了个小目标,最近的电影哪吒很火,去豆瓣上看了一下 影评,决定了今天主要是实现Python第三个项目:爬取豆瓣<哪吒之魔童降世> 短评,然后下载在exce ...

  6. 孤荷凌寒自学python第三十八天初识python的线程控制

    孤荷凌寒自学python第三十八天初识python的线程控制 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 一.线程 在操作系统中存在着很多的可执行的应用程序,每个应用程序启动后,就可以看着 ...

  7. python判断哪个数最小_怎么用python比较三个数大小

    大部分初学编程的人来说刚开始都会练习判断两个数或者三个数的大小,来熟悉某种语言的特性和最基本的if,else循环,当我们学习了更高级的语法知识后,又会有不同的实现方式,比如依次接收用户输入的3个数,排 ...

  8. python中三个双引号 的作用是什么?1、多行注释 2、定义多行字符串(代替转义字符换行符 \n)

    作用1:多行注释 # 这是单行注释""" 这是多行注释第一行 这是多行注释第二行 这是多行注释第三行 """ 作用2:定义多行字符串(无需转 ...

  9. python求三个整数最大值_怎么用python比较三个数大小

    大部分初学编程的人来说刚开始都会练习判断两个数或者三个数的大小,来熟悉某种语言的特性和最基本的if,else循环,当我们学习了更高级的语法知识后,又会有不同的实现方式,比如依次接收用户输入的3个数,排 ...

最新文章

  1. Sap Byd Soap使用 SSL 客户端证书
  2. 怎样才能学好Vue,听听尤雨溪怎么说?
  3. Setting up Pytorch with Python 3 on Ubuntu(Source code compilation)
  4. android 9.x 实现应用内更新安装
  5. amixer 如何切通道_三峡工程如何突破技术难题?
  6. 如何通过 C# 实现对象的变更跟踪 ?
  7. 前端学习(1889)vue之电商管理系统电商系统之绘制用户列表组件的基本布局
  8. hadoop MultipleInputs fails with ClassCastException (get fileName)
  9. 夫曼编码译码系统课程设计实验报告(含源代码c++_c语言),哈夫曼编码译码系统课程设计实验报告(含源代码C++_C语言)[1]...
  10. 易安卓 html5,Developing a Multi Platforms Web Applications for Mobile Device Using HTML5
  11. php 网站域名怎么更换,教你如何快速给网站更换域名,简单粗暴!
  12. c# 去除字符串中的换行符 \r\n
  13. (对比PDF)Adobe Acrobat DC 离线对比PDF、draftable.com/compare 在线对比PDF
  14. STM32的CAN波特率设置方法详解
  15. SQL创建触发器以及触发器的使用实例+详解
  16. Hook Android q 剪贴板限制,AndroidQ(10)获取剪切板内容适配
  17. 如何使用REST Assured执行API测试
  18. 陈小龙书pHP,PHP
  19. 电信联通共享检测技术及防封杀
  20. 【机器人】工业机器人如何赋能3C制造升级?工业机器人的16项重要应用;工业机器人的11个知识问答,“业内人”必看!

热门文章

  1. vscode 不支持的客户端_Windows平台上有哪些你不知道的神器?
  2. load data infile mysql_mysql Load Data InFile 的用法举例
  3. HTML背景颜色长宽高怎么设置,Dreamweaver 8怎么通过代码设置页面高宽颜色
  4. python 增量备份mysql_Python 生产环境MySQL数据库增量备份脚本
  5. PowerDesigner的基本使用
  6. 一级计算机考试中的DBF,2017年计算机等考一级WPS2000辅导:使用DBF格式内容的方法...
  7. python文本数据处理_python 数据处理 对txt文件进行数据处理
  8. 机器学习、数据挖掘之中国大牛
  9. 动态内存分配(malloc函数)
  10. java 声明数组_Java中的数组简介