1.python处理xml代码如下
import datetime
import xml.dom.minidom
import random
import re
import sys
filename=sys.argv[1] #打包成exe并接收参数
#filename='samplexml.txt' #本地调试用
filepath=''+filename
with open(filepath,'r',encoding='utf-8') as f:#文档预处理为utf-8格式
content=f.read()
newcontent=[line for line in content.splitlines() if line.strip()] #去掉空行
datasource='\n'.join(newcontent)
f.close()
tree=xml.dom.minidom.parseString(datasource) #minidom模块只支持utf-8格式文档
num=str(random.randint(10000000,99999999))
#获取某个标签
ele01=tree.getElementsByTagName('id')[0]
newid='202402213000'+num
ele01.firstChild.data=newid
ele02=tree.getElementsByTagName('author')[2]
ele02.firstChild.data='Bella'
now=datetime.datetime.now()
time=str(datetime.datetime.timestamp(now))
timestr=time.replace('.','')
resultname=filename.replace('.txt','_')+timestr+'.txt'
with open(resultname,'w',encoding='GBK') as f:
tree.writexml(f,addindent='',newl='\n',encoding='GBK')
2.安装pyinstaller
3.打包成带一个参数的exe,打包好的文件在dist文件夹下
4.执行exe
因为传的参数就是一个文件,事先把文件放到exe文件同级的目录下。
用以下命令进行执行。没报错,且生成了新文件就算执行成功了
注意:要处理的xml文件不能带注释。
smaplexml.txt内容如下:
<?xml version="1.0" encoding="GBK"?>
<bookstore>
<book category="cooking">
<id>2024021312345678</id>
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<id>2024021312345679</id>
<title lang="en">Harry Potter</title>
<author>J.K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<id>2024021312345676</id>
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>