模块

本文介绍了使用Python进行文件操作、XML解析与修改的具体方法,包括执行系统命令、文件复制与压缩、读写shelve数据库及解析和生成XML文件等实用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import os,sys,shutil,zipfile,shelve
##os文件模块
print(os.environ['os'])
os.system('dir') #执行系统命令
a=os.popen('dir').read()  #执行dir命令 当做临时文件,然后read()
print(a,'\n-------------------------')
print(os.stat('info')) #文件的信息
print(os.path.abspath(__file__)) #文件的绝对路径
print(os.path.isfile('info')) #是否是文件,或者isdir目录

#sys模块
print(sys.argv) #当前文件
print(sys.stdout.write('please:'))
print(sys.platform) #系统

##shutil 高级文件,压缩,处理
shutil.copyfile('info','test')

# shutil.make_archive('../test','zip','../day4') #压缩

# 解压
z=zipfile.ZipFile('../test.zip','r')
z.extractall('../test/')
z.close()


shelve模块

import shelve
#shelve pickle再次封装
s=shelve.open('shelve_test')
name=['laowang','21',22]
s['name']=name
s['b']=[1,23]
s.close()


a=shelve.open('shelve_test')
b=a.get('name')
print(a.get('name'))
print(a.get('b'))

xml模块

import xml.etree.ElementTree as ET
#xml模块
tree = ET.parse('test.xml')
root = tree.getroot()
print(root.tag)  # 根节点的名字
#
for child in root:
    print(child.tag, child.attrib)
    for i in child:
        print('---->', 'tag:', i.tag, '\ntext:', i.text, '\nattrib:', i.attrib)

print('\n-------------------\n')

# 修改
for node in root.iter('year'):
    print(node.tag, node.text)
    new_year = int(node.text) + 1
    # 年份加1
    node.text = str(new_year)
    # year节点添加属性
    node.set('update', 'yes')
tree.write('xmlchange.xml')

# 删除
for country in root.findall('country'):
    rank = int(country.find('rank').text)
    if rank > 50:
        root.remove(country)
tree.write('xmldel.xml')

# 生成
create_xml = ET.Element('namelist')

name = ET.SubElement(create_xml, 'name', attrib={'enrolled': 'yes'})
age = ET.SubElement(name, 'age', attrib={'checked': 'no'})
sex = ET.SubElement(name, 'sex')
age.text = '29'
sex.text = 'male'

name = ET.SubElement(create_xml,'name',attrib={'enrolled':'no'})
age=ET.SubElement(name,'age')
age.text='33'
et=ET.ElementTree(create_xml)
et.write('create_xml.xml',encoding='utf-8',xml_declaration=True)



<?xml version="1.0" encoding="utf-8" ?>
<alex>
    <country name="guojia1">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <neighbor name="neighbor1" direction="E"/>
        <neighbor name="neighbor2" direction="R"/>
    </country>
    <country name="guojia2">
        <rank updated="yes">200</rank>
        <year>2008</year>
        <neighbor name="guojia2_neighbor1" direction="c"/>
        <neighbor name="guojia2_neighbor2" direction="w"/>
    </country>
</alex>
#md5模块
import hashlib
md5 = hashlib.md5()
md5.update(b'123456')
print(md5.hexdigest())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值