python 实现遍里文件夹操作xml文件
上次发了Java操作的,今天来篇python操作的,上代码:
import os.path import xml.dom.minidom # path = '/home/kanghao/learning_something/about_xml/xml/' path = 'C:/Users/Administrator/Desktop/37227' files = os.listdir(path) # 得到文件夹下所有文件名称 for xmlFile in files: # 遍历文件夹 if not os.path.isdir(xmlFile): # 判断是否是文件夹,不是文件夹才打开 print('文件名称:' + xmlFile) dom = xml.dom.minidom.parse(os.path.join(path, xmlFile)) # 将获取的xml文件名送入到dom解析 root = dom.documentElement y = root.getElementsByTagName('smr') if len(y) == 0: measure = dom.getElementsByTagName('measurement')[0] # 获取上层节点 smr = dom.createElement('smr') # 创建要添加的节点 obj = dom.getElementsByTagName('object')[0] # 获取下层节点 measure.insertBefore(smr, obj) # 将节点在下层节点之前添加到上层节点 smrValue = dom.createTextNode('MR.LteScRSRP MR.LteScRSRQ MR.LteScEarfcn MR.LteScPci MR.LteScCgi ' 'MR.LteNcRSRP MR.LteNcRSRQ MR.LteNcEarfcn MR.LteNcPci MR.GsmNcellBcch ' 'MR.GsmNcellCarrierRSSI MR.GsmNcellNcc MR.GsmNcellBcc MR.UtraCpichRSCP ' 'MR.UtraCarrierRSSI MR.UtraCpichEcNo MR.UtraCellParameterId') smr.appendChild(smrValue) # 给<smr>节点添加值 x = root.getElementsByTagName('v') ###获取标签对v的值 print(len(x)) for i in range(len(x)): n0 = x[i] isl = n0.firstChild.data.find(' ') if isl == -1: n0.firstChild.data = int(n0.firstChild.data) - 135 else: n0.firstChild.data = str(int(n0.firstChild.data[0:isl]) - 135) + n0.firstChild.data[isl:] # 修改数据 with open(os.path.join(path, xmlFile), 'w') as fh: dom.writexml(fh)
小白技术分享