python之day7
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python之day7相关的知识,希望对你有一定的参考价值。
今日上课的主要内容
一,模块:
二,面向对象(上):
作业(计算器):
http://www.cnblogs.com/wupeiqi/articles/4949995.html
模块:
configparser:都会按照字符串进行处理
import configparser
config = configparser.ConfigParser()
config.read(‘xxxooo‘, encoding=‘utf-8‘)
练习:
import configparser config = configparser.ConfigParser() config.read(‘f1‘,encoding=‘utf-8‘) ret = config.sections() print(ret) ret = config.items("section2") print(ret) ret = config.options(‘section2‘) print(ret) v = config.get(‘section1‘, ‘k1‘) print(v) has_sec = config.has_section(‘section1‘) print(has_sec) # config.add_section("section3") # config.write(open(‘xxxooo‘, ‘w‘)) # # config.remove_section("section3") # config.write(open(‘xxxooo‘, ‘w‘)) has_opt = config.has_option(‘section1‘, ‘k1‘) print(has_opt) config.remove_option(‘section1‘, ‘k1‘) config.write(open(‘xxxooo‘, ‘w‘)) config.set(‘section1‘, ‘k10‘, "123") config.write(open(‘xxxooo‘, ‘w‘))
XML:
浏览器返回的字符串
1,html
2,json
3,xml
页面上做展示(字符串类型的一个XML格式数据)
配置文件(文件,内部数据XML格式)
每一个节点都是 element的对象
练习1:
from xml.etree import ElementTree as ET tree = ET.parse(‘xo.xml‘) root = tree.getroot() for child in root: print(child.tag,child.attrib) for grandchild in child: print(grandchild.tag,grandchild.attrib) str_xml = open(‘xo.xml‘, ‘r‘).read() root = ET.XML(str_xml) for node in root.iter(‘year‘): new_year = int(node.text) + 1 node.text = str(new_year) # 设置属性 node.set(‘name‘, ‘alex‘) node.set(‘age‘, ‘18‘) # 删除属性 del node.attrib[‘name‘] tree = ET.ElementTree(root) tree.write(‘new.xml‘,encoding=‘utf-8‘) tree = ET.parse(‘xo.xml‘) root = tree .getroot() for node in root.iter(‘year‘): new_year = int(node.text) + 1 node.text = str(new_year) node.set(‘age‘,‘18‘) node.set(‘name‘,‘sxl‘) del node.attrib[‘name‘] tree.write(‘new2.xml‘,encoding=‘utf-8‘)
练习2:
from xml.etree import ElementTree as ET from xml.dom import minidom def prettify(elem): """将节点转换成字符串,并添加缩进。 """ rough_string = ET.tostring(elem, ‘utf-8‘) reparsed = minidom.parseString(rough_string) return reparsed.toprettyxml(indent="\\t") root = ET.Element(‘famliy‘) son1 = ET.Element(‘son1‘,{‘name‘:‘大儿子‘}) son2 = ET.Element(‘son2‘,{‘name‘:‘小儿子‘}) grandson1 = ET.Element(‘grandson‘, {‘name‘: ‘儿11‘}) grandson2 = ET.Element(‘grandson‘, {‘name‘: ‘儿22‘}) son1.append(grandson1) son2.append(grandson2) root.append(son1) root.append(son2) raw_str = prettify(root) tree = ET.ElementTree(root) tree.write(‘oooo.xml‘,encoding=‘utf-8‘, short_empty_elements=False) f = open("xxxoo.xml",‘w‘,encoding=‘utf-8‘) f.write(raw_str) f.close()
以上是关于python之day7的主要内容,如果未能解决你的问题,请参考以下文章