码迷,mamicode.com
首页 > 其他好文 > 详细

Day6-常用模块

时间:2018-01-17 23:28:31      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:jin   文档   格式化   unp   a*   练习   有符号   time   拷贝文件   

1.re模块

技术分享图片

# =================================匹配模式=================================
#一对一的匹配
# ‘hello‘.replace(old,new)
# ‘hello‘.find(‘pattern‘)

#正则匹配
import re
#\w与\W
print(re.findall(‘\w‘,‘hello egon 123‘)) #[‘h‘, ‘e‘, ‘l‘, ‘l‘, ‘o‘, ‘e‘, ‘g‘, ‘o‘, ‘n‘, ‘1‘, ‘2‘, ‘3‘]
print(re.findall(‘\W‘,‘hello egon 123‘)) #[‘ ‘, ‘ ‘]

#\s与\S
print(re.findall(‘\s‘,‘hello  egon  123‘)) #[‘ ‘, ‘ ‘, ‘ ‘, ‘ ‘]
print(re.findall(‘\S‘,‘hello  egon  123‘)) #[‘h‘, ‘e‘, ‘l‘, ‘l‘, ‘o‘, ‘e‘, ‘g‘, ‘o‘, ‘n‘, ‘1‘, ‘2‘, ‘3‘]

#\n \t都是空,都可以被\s匹配
print(re.findall(‘\s‘,‘hello \n egon \t 123‘)) #[‘ ‘, ‘\n‘, ‘ ‘, ‘ ‘, ‘\t‘, ‘ ‘]

#\n与\t
print(re.findall(r‘\n‘,‘hello egon \n123‘)) #[‘\n‘]
print(re.findall(r‘\t‘,‘hello egon\t123‘)) #[‘\n‘]

#\d与\D
print(re.findall(‘\d‘,‘hello egon 123‘)) #[‘1‘, ‘2‘, ‘3‘]
print(re.findall(‘\D‘,‘hello egon 123‘)) #[‘h‘, ‘e‘, ‘l‘, ‘l‘, ‘o‘, ‘ ‘, ‘e‘, ‘g‘, ‘o‘, ‘n‘, ‘ ‘]

#\A与\Z
print(re.findall(‘\Ahe‘,‘hello egon 123‘)) #[‘he‘],\A==>^
print(re.findall(‘123\Z‘,‘hello egon 123‘)) #[‘he‘],\Z==>$

#^与$
print(re.findall(‘^h‘,‘hello egon 123‘)) #[‘h‘]
print(re.findall(‘3$‘,‘hello egon 123‘)) #[‘3‘]

# 重复匹配:| . | * | ? | .* | .*? | + | {n,m} |
#.
print(re.findall(‘a.b‘,‘a1b‘)) #[‘a1b‘]
print(re.findall(‘a.b‘,‘a1b a*b a b aaab‘)) #[‘a1b‘, ‘a*b‘, ‘a b‘, ‘aab‘]
print(re.findall(‘a.b‘,‘a\nb‘)) #[]
print(re.findall(‘a.b‘,‘a\nb‘,re.S)) #[‘a\nb‘]
print(re.findall(‘a.b‘,‘a\nb‘,re.DOTALL)) #[‘a\nb‘]同上一条意思一样

#*
print(re.findall(‘ab*‘,‘bbbbbbb‘)) #[]
print(re.findall(‘ab*‘,‘a‘)) #[‘a‘]
print(re.findall(‘ab*‘,‘abbbb‘)) #[‘abbbb‘]

#?
print(re.findall(‘ab?‘,‘a‘)) #[‘a‘]
print(re.findall(‘ab?‘,‘abbb‘)) #[‘ab‘]
#匹配所有包含小数在内的数字
print(re.findall(‘\d+\.?\d*‘,"asdfasdf123as1.13dfa12adsf1asdf3")) #[‘123‘, ‘1.13‘, ‘12‘, ‘1‘, ‘3‘]

#.*默认为贪婪匹配
print(re.findall(‘a.*b‘,‘a1b22222222b‘)) #[‘a1b22222222b‘]

#.*?为非贪婪匹配:推荐使用
print(re.findall(‘a.*?b‘,‘a1b22222222b‘)) #[‘a1b‘]

#+
print(re.findall(‘ab+‘,‘a‘)) #[]
print(re.findall(‘ab+‘,‘abbb‘)) #[‘abbb‘]

#{n,m}
print(re.findall(‘ab{2}‘,‘abbb‘)) #[‘abb‘]
print(re.findall(‘ab{2,4}‘,‘abbb‘)) #[‘abb‘]
print(re.findall(‘ab{1,}‘,‘abbb‘)) #‘ab{1,}‘ ===> ‘ab+‘
print(re.findall(‘ab{0,}‘,‘abbb‘)) #‘ab{0,}‘ ===> ‘ab*‘

#[]
print(re.findall(‘a[1*-]b‘,‘a1b a*b a-b‘)) #[]内的都为普通字符了,且如果-没有被转意的话,应该放到[]的开头或结尾
print(re.findall(‘a[^1*-]b‘,‘a1b a*b a-b a=b‘)) #[]内的^代表的意思是取反,所以结果为[‘a=b‘]
print(re.findall(‘a[0-9]b‘,‘a1b a*b a-b a=b‘)) #[]内的^代表的意思是取反,所以结果为[‘a=b‘]
print(re.findall(‘a[a-z]b‘,‘a1b a*b a-b a=b aeb‘)) #[]内的^代表的意思是取反,所以结果为[‘a=b‘]
print(re.findall(‘a[a-zA-Z]b‘,‘a1b a*b a-b a=b aeb aEb‘)) #[]内的^代表的意思是取反,所以结果为[‘a=b‘]

#\# print(re.findall(‘a\\c‘,‘a\c‘)) #对于正则来说a\\c确实可以匹配到a\c,但是在python解释器读取a\\c时,会发生转义,然后交给re去执行,所以抛出异常
print(re.findall(r‘a\\c‘,‘a\c‘)) #r代表告诉解释器使用rawstring,即原生字符串,把我们正则内的所有符号都当普通字符处理,不要转义
print(re.findall(‘a\\\\c‘,‘a\c‘)) #同上面的意思一样,和上面的结果一样都是[‘a\\c‘]

#():分组
print(re.findall(‘ab+‘,‘ababab123‘)) #[‘ab‘, ‘ab‘, ‘ab‘]
print(re.findall(‘(ab)+123‘,‘ababab123‘)) #[‘ab‘],匹配到末尾的ab123中的ab
print(re.findall(‘(?:ab)+123‘,‘ababab123‘)) #findall的结果不是匹配的全部内容,而是组内的内容,?:可以让结果为匹配的全部内容
print(re.findall(‘href="(.*?)"‘,‘<a href="http://www.baidu.com">点击</a>‘))#[‘http://www.baidu.com‘]
print(re.findall(‘href="(?:.*?)"‘,‘<a href="http://www.baidu.com">点击</a>‘))#[‘href="http://www.baidu.com"‘]

#|
print(re.findall(‘compan(?:y|ies)‘,‘Too many companies have gone bankrupt, and the next one is my company‘))

# ===========================re模块提供的方法介绍===========================
import re
#1
print(re.findall(‘e‘,‘alex make love‘) )   #[‘e‘, ‘e‘, ‘e‘],返回所有满足匹配条件的结果,放在列表里
#2
print(re.search(‘e‘,‘alex make love‘).group()) #e,只到找到第一个匹配然后返回一个包含匹配信息的对象,该对象可以通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None。

#3
print(re.match(‘e‘,‘alex make love‘))    #None,同search,不过在字符串开始处进行匹配,完全可以用search+^代替match

#4
print(re.split(‘[ab]‘,‘abcd‘))     #[‘‘, ‘‘, ‘cd‘],先按‘a‘分割得到‘‘和‘bcd‘,再对‘‘和‘bcd‘分别按‘b‘分割

#5
print(‘===>‘,re.sub(‘a‘,‘A‘,‘alex make love‘)) #===> Alex mAke love,不指定n,默认替换所有
print(‘===>‘,re.sub(‘a‘,‘A‘,‘alex make love‘,1)) #===> Alex make love
print(‘===>‘,re.sub(‘a‘,‘A‘,‘alex make love‘,2)) #===> Alex mAke love
print(‘===>‘,re.sub(‘^(\w+)(.*?\s)(\w+)(.*?\s)(\w+)(.*?)$‘,r‘\5\2\3\4\1‘,‘alex make love‘)) #===> love make alex

print(‘===>‘,re.subn(‘a‘,‘A‘,‘alex make love‘)) #===> (‘Alex mAke love‘, 2),结果带有总共替换的个数

#6
obj=re.compile(‘\d{2}‘)

print(obj.search(‘abc123eeee‘).group()) #12
print(obj.findall(‘abc123eeee‘)) #[‘12‘],重用了obj

2.time模块

import time
#--------------------------我们先以当前时间为准,让大家快速认识三种形式的时间
print(time.time()) # 时间戳:1487130156.419527
print(time.strftime("%Y-%m-%d %X")) #格式化的时间字符串:‘2017-02-15 11:40:53‘

print(time.localtime()) #本地时区的struct_time
print(time.gmtime())    #UTC时区的struct_time

技术分享图片

#--------------------------按图1转换时间
# localtime([secs])
# 将一个时间戳转换为当前时区的struct_time。secs参数未提供,则以当前时间为准。
time.localtime()
time.localtime(1473525444.037215)

# gmtime([secs]) 和localtime()方法类似,gmtime()方法是将一个时间戳转换为UTC时区(0时区)的struct_time。

# mktime(t) : 将一个struct_time转化为时间戳。
print(time.mktime(time.localtime()))#1473525749.0

# strftime(format[, t]) : 把一个代表时间的元组或者struct_time(如由time.localtime()和
# time.gmtime()返回)转化为格式化的时间字符串。如果t未指定,将传入time.localtime()。如果元组中任何一个
# 元素越界,ValueError的错误将会被抛出。
print(time.strftime("%Y-%m-%d %X", time.localtime()))#2016-09-11 00:49:56

# time.strptime(string[, format])
# 把一个格式化时间字符串转化为struct_time。实际上它和strftime()是逆操作。
print(time.strptime(‘2011-05-05 16:37:06‘, ‘%Y-%m-%d %X‘))
#time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=16, tm_min=37, tm_sec=6,
#  tm_wday=3, tm_yday=125, tm_isdst=-1)
#在这个函数中,format默认为:"%a %b %d %H:%M:%S %Y"。

3.logging模块

#日志模块的详细用法:
import logging
#1、Logger:产生日志
logger1=logging.getLogger("访问日志")
#2、Filter:

#3、Handler:接受传过来的日志,进行日志格式化,可以打印到终端或者文件
sh=logging.StreamHandler()#打印到终端
fh1 = logging.FileHandler(‘s1.log‘,encoding=‘utf-8‘)
fh2 = logging.FileHandler(‘s2.log‘,encoding=‘utf-8‘)

#4、Formatter:日志格式
formatter1 = logging.Formatter(
    fmt=‘%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s‘,
    datefmt=‘%Y-%m-%d %H:%M:%S %p‘,
)
formatter2 = logging.Formatter(
    fmt=‘%(asctime)s - %(message)s‘,
    datefmt=‘%Y-%m-%d %H:%M:%S %p‘,
)

formatter3=logging.Formatter(
    fmt=‘%(asctime)s : %(module)s : %(message)s‘,
    datefmt=‘%Y-%m-%d %H:%M:%S %p‘,
)

#5、为handler绑定日志格式
# sh.setFormatter()

4.random模块

#random 生成随机数模块

import random
# random.randint(a,b) [a,b]生成a到b之前的随机整数
# random.random() (0,1) 生成0到1之间的随机小数
# random.choice()
# random.randrange() [a,b) 生成a到b之间的随机整数
# random.uniform() (a,b) 生成a到b之间的随机小数
# 练习:编写一个随机验证码的函数,验证码包含数字,字母大小写

def make_code(n):
    res = ""
    for i in range(n):
        s1 = str(random.randint(0,9))
        s2 = chr(random.randint(65,90))
        s3 = chr(random.randint(97,122))
        res += random.choice([s1,s2,s3])
    return res

print(make_code(9))
# print(random.random())
# print(random.choice([‘1‘,‘2‘,‘3‘]),2)
# print(random.randrange(1,3))
# print(random.uniform(1,3))

#洗牌操作
item=[1,2,3,4,5,6,7,8,9,10,‘J‘,‘Q‘,‘K‘]
random.shuffle(item)
print(item)

5.os 模块

import os,sys

#拼接项目所在跟路径
print(os.path.normpath(os.path.join(
    os.path.abspath(__file__),
    ‘..‘,
    ‘..‘
)))
# print(os.path.dirname(__file__)) #获取当前文件的目录路径
# print(os.path.abspath(__file__)) #获取当前文件的绝对路径
# print(os.path.exists(__file__)) #判断文件是否存在
# print(os.path.join(‘C:‘,‘a‘,‘D:‘,‘b‘,‘c‘)) #从最右边的根目录开始拼接文件路径
print(os.path.split(‘D:b\c\d\a.txt‘)) #将路径拆成分
# print(os.name) #操作系统的类型
# print(os.pardir) #上级目录

6.sys模块

import sys,time,os

#打印进度条
def progress(percent,width=50):
    ‘‘‘print process ‘‘‘
    if percent > 1:
        percent = 1
    show_str = ((‘[%%-%ds]‘ %width) %(‘#‘*int(percent*width)))
    print(‘\r%s %d%%‘ %(show_str,int(percent*100)),end=‘‘)

revc_size = 0
total_size = 10242

while revc_size < total_size:
    revc_size+=1024
    time.sleep(0.1)
    progress(revc_size/total_size)

#打印进度条  简版
# for n in range(50):
#     sys.stdout.write(‘#‘)
#     sys.stdout.flush()
#     time.sleep(0.05)

# sys.argv[1]  #传入的第一个参数
# print(sys.path ) #打印系统环境变量
# sys.exit(n) # 定义退出时的状态码
# print(sys.platform) #系统的类型

7.json/pikle模块

之前我们学习过用eval内置方法可以将一个字符串转成python对象,不过,eval方法是有局限性的,对于普通的数据类型,json.loads和eval都能用,但遇到特殊类型的时候,eval就不管用了,所以eval的重点还是通常用来执行一个字符串表达式,并返回表达式的值。

1 import json
2 x="[null,true,false,1]"
3 print(eval(x)) #报错,无法解析null类型,而json就可以
4 print(json.loads(x)) 
什么是序列化?

我们把对象(变量)从内存中变成可存储或传输的过程称之为序列化,在Python中叫pickling,在其他语言中也被称之为serialization,marshalling,flattening等等,都是一个意思。

为什么要序列化?

1:持久保存状态

需知一个软件/程序的执行就在处理一系列状态的变化,在编程语言中,‘状态‘会以各种各样有结构的数据类型(也可简单的理解为变量)的形式被保存在内存中。

内存是无法永久保存数据的,当程序运行了一段时间,我们断电或者重启程序,内存中关于这个程序的之前一段时间的数据(有结构)都被清空了。

在断电或重启程序之前将程序当前内存中所有的数据都保存下来(保存到文件中),以便于下次程序执行能够从文件中载入之前的数据,然后继续执行,这就是序列化。

具体的来说,你玩使命召唤闯到了第13关,你保存游戏状态,关机走人,下次再玩,还能从上次的位置开始继续闯关。或如,虚拟机状态的挂起等。

2:跨平台数据交互

序列化之后,不仅可以把序列化后的内容写入磁盘,还可以通过网络传输到别的机器上,如果收发的双方约定好实用一种序列化的格式,那么便打破了平台/语言差异化带来的限制,实现了跨平台数据交互。

反过来,把变量内容从序列化的对象重新读到内存里称之为反序列化,即unpickling。

如何序列化之json和pickle:

json

如果我们要在不同的编程语言之间传递对象,就必须把对象序列化为标准格式,比如XML,但更好的方法是序列化为JSON,因为JSON表示出来就是一个字符串,可以被所有语言读取,也可以方便地存储到磁盘或者通过网络传输。JSON不仅是标准格式,并且比XML更快,而且可以直接在Web页面中读取,非常方便。

JSON表示的对象就是标准的JavaScript语言的对象,JSON和Python内置的数据类型对应如下:

技术分享图片
技术分享图片

import json

dic={‘name‘:‘alvin‘,‘age‘:23,‘sex‘:‘male‘}
print(type(dic))#<class ‘dict‘>

j=json.dumps(dic)
print(type(j))#<class ‘str‘>

f=open(‘序列化对象‘,‘w‘)
f.write(j)  #-------------------等价于json.dump(dic,f)
f.close()
#-----------------------------反序列化<br>
import json
f=open(‘序列化对象‘)
data=json.loads(f.read())#  等价于data=json.load(f)

import json
#dct="{‘1‘:111}"#json 不认单引号
#dct=str({"1":111})#报错,因为生成的数据还是单引号:{‘one‘: 1}

dct=‘{"1":"111"}‘
print(json.loads(dct))

#conclusion:
#        无论数据是怎样创建的,只要满足json格式,就可以json.loads出来,不一定非要dumps的数据才能loads

 注意点

技术分享图片

import pickle

dic={‘name‘:‘alvin‘,‘age‘:23,‘sex‘:‘male‘}

print(type(dic))#<class ‘dict‘>

j=pickle.dumps(dic)
print(type(j))#<class ‘bytes‘>

f=open(‘序列化对象_pickle‘,‘wb‘)#注意是w是写入str,wb是写入bytes,j是‘bytes‘
f.write(j)  #-------------------等价于pickle.dump(dic,f)

f.close()
#-------------------------反序列化
import pickle
f=open(‘序列化对象_pickle‘,‘rb‘)

data=pickle.loads(f.read())#  等价于data=pickle.load(f)

print(data[‘age‘])

8.configparse模块

对类似于mysql php等配置文件进行操作

import configparser
config = configparser.ConfigParser()

config.read(‘my.ini‘)
#增加配置项
# config.add_section(‘mysqld‘)
# config.set(‘mysqld‘,‘port‘,‘3306‘)
# config.set(‘mysqld‘,‘character-server-set‘,‘utf8‘)
# config.set(‘mysqld‘,‘db-engin‘,‘innodb‘)
#
# config.add_section(‘client‘)
# config.set(‘client‘,‘name‘,‘huazai‘)
# config.set(‘client‘,‘password‘,‘123456‘)

#修改配置项
config.set(‘client‘,‘password‘,‘abc123‘)
config.write(open(‘my.ini‘,‘w‘,encoding=‘utf-8‘))  #最后

# config.add_section(‘hehe‘)
#查看section下的配置内容
print(config.get(‘mysqld‘,‘port‘))

9.hashlib模块

#hashlib加密三个特点:
    #hash值长度固定
    #不可逆
    #str相同加密后,hash值相同
#用途:
#文件下载,校验文件的完整

# import hashlib
# md5=hashlib.md5()
# md5.update(‘hello‘.encode(‘utf-8‘))
# md5.update(‘hello‘.encode(‘utf-8‘))
# print(md5.hexdigest())

#加盐
# import hashlib
# md5 = hashlib.md5()
# md5.update(‘两个黄鹂鸣翠柳‘.encode(‘utf-8‘))
# md5.update(‘hello‘.encode(‘utf-8‘))
# md5.update(‘一行白鹭上青天‘.encode(‘utf-8‘))
# print(md5.hexdigest())
# md = hashlib.md5()
#
# md.update(‘两个黄鹂鸣翠柳hello一行白鹭上青天‘.encode(‘utf-8‘))
# print(md.hexdigest())

import hmac
h=hmac.new(‘slat‘.encode(‘utf-8‘))
h.update(‘hello‘.encode(‘utf-8‘))
print(h.hexdigest())

10.shutil模块

import shutil
#对文件操作
# shutil.copyfileobj() #将文件内容拷贝到另一个文件中
# shutil.copyfile() #拷贝文件
# shutil.copymode() #仅拷贝权限。内容、组、用户均不变
# shutil.copystat() #仅拷贝状态的信息,包括:mode bits, atime, mtime, flags
# shutil.copy() #拷贝文件和权限
# shutil.copy2() #拷贝文件和状态信息
# shutil.copytree() #递归的去拷贝文件夹
# shutil.ignore_patterns() #忽略一些文件,和其他命令组合使用
# shutil.rmtree() #递归的去删除文件
# shutil.move() #递归的去移动文件,它类似mv命令,其实就是重命名。
# shutil.make_archive() #创建压缩包并返回文件路径
# 将 /data 下的文件打包放置当前程序目录
import shutil

# ret = shutil.make_archive("data_bak", ‘gztar‘, root_dir=‘/data‘)

# 将 /data下的文件打包放置 /tmp/目录
import shutil

ret = shutil.make_archive("/tmp/data_bak", ‘gztar‘, root_dir=‘/data‘)

11.shelve模块

 # shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写;key必须为字符串,而值可以是python所支持的数据类型

import shelve

f=shelve.open(r‘sheve.txt‘)
# f[‘stu1_info‘]={‘name‘:‘egon‘,‘age‘:18,‘hobby‘:[‘piao‘,‘smoking‘,‘drinking‘]}
# f[‘stu2_info‘]={‘name‘:‘gangdan‘,‘age‘:53}
# f[‘school_info‘]={‘website‘:‘http://www.pypy.org‘,‘city‘:‘beijing‘}

print(f[‘stu1_info‘][‘hobby‘])
f.close()

12.xml模块

xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml呀,至今很多传统公司如金融行业的很多系统的接口还主要是xml。

xml的格式如下,就是通过<>节点来区别数据结构的:

xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml呀,至今很多传统公司如金融行业的很多系统的接口还主要是xml。

xml的格式如下,就是通过<>节点来区别数据结构的:

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <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协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml:

# print(root.iter(‘year‘)) #全文搜索
# print(root.find(‘country‘)) #在root的子节点找,只找一个
# print(root.findall(‘country‘)) #在root的子节点找,找所有

import xml.etree.ElementTree as ET

tree = ET.parse("xmltest.xml")
root = tree.getroot()
print(root.tag)

#遍历xml文档
for child in root:
    print(‘========>‘,child.tag,child.attrib,child.attrib[‘name‘])
    for i in child:
        print(i.tag,i.attrib,i.text)

#只遍历year 节点
for node in root.iter(‘year‘):
    print(node.tag,node.text)
#---------------------------------------

import xml.etree.ElementTree as ET

tree = ET.parse("xmltest.xml")
root = tree.getroot()

#修改
for node in root.iter(‘year‘):
    new_year=int(node.text)+1
    node.text=str(new_year)
    node.set(‘updated‘,‘yes‘)
    node.set(‘version‘,‘1.0‘)
tree.write(‘test.xml‘)

#删除node
for country in root.findall(‘country‘):
   rank = int(country.find(‘rank‘).text)
   if rank > 50:
     root.remove(country)

tree.write(‘output.xml‘)

#在country内添加(append)节点year2
import xml.etree.ElementTree as ET
tree = ET.parse("a.xml")
root=tree.getroot()
for country in root.findall(‘country‘):
    for year in country.findall(‘year‘):
        if int(year.text) > 2000:
            year2=ET.Element(‘year2‘)
            year2.text=‘新年‘
            year2.attrib={‘update‘:‘yes‘}
            country.append(year2) #往country节点下添加子节点

tree.write(‘a.xml.swap‘)

自己创建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")
sex.text = ‘33‘
name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})
age = ET.SubElement(name2,"age")
age.text = ‘19‘

et = ET.ElementTree(new_xml) #生成文档对象
et.write("test.xml", encoding="utf-8",xml_declaration=True)

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

Day6-常用模块

标签:jin   文档   格式化   unp   a*   练习   有符号   time   拷贝文件   

原文地址:http://blog.51cto.com/ronghuachen/2062208

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!