[英]Delete a specific part of a file python
I work under python 3.2 on Windows (8.1), and I have an XML file in which I would like to delete a specific part if this one exists. 我在Windows(8.1)上的python 3.2下工作,并且我有一个XML文件,如果有此特定部分,我想在其中删除。 Here is the visual example of what I need to do:
这是我需要做的视觉示例:
I would like to know how we could delete the selected part in the picture, knowing that there can be or not several occurences of . 我想知道如何可以删除图片中的选定部分,因此我想知道该如何删除。
You can use xml.etree.ElementTree: https://docs.python.org/2/library/xml.etree.elementtree.html#modifying-an-xml-file 您可以使用xml.etree.ElementTree: https ://docs.python.org/2/library/xml.etree.elementtree.html#modifying-an-xml-file
from xml.etree import ElementTree
with open('file.xml', 'rt') as f:
tree = ElementTree.parse(f)
root = tree.getroot()
for node in root.iter():
if node.tag == 'object2':
root.remove(node)
tree.write(out.xml)
import re
f=open("some.xml",'r')
f.close()
x=f.read()
y=re.sub(r"<object2>(?:(?!<\/object2>)[\s\S])*<\/object2>","",x)
f=open("some.xml",'w')
f.write(y)
f.close()
You can try this using re
. 您可以使用
re
尝试此操作。
f = open('xmlfile.xml','r')
flag = False
tempData = ''
for line in f:
if '<object2>' in line:
flag = True
elif flag == True and '</object2>' in line:
flag = False
elif flag == False:
tempData += line
f.close()
f = open('xmlfile.xml','w')
f.write(tempData)
f.close()
A little longer than vks' answer, but it does not require an import. 比vks的回答稍长,但是不需要导入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.