python处理xml并打包成exe带参数运行

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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值