[英]Python: Remove everything before certain chars
我有幾個應該處理的文件。 這些文件是xml文件,但是在“ <?xml version =” 1.0“?>”之前,有一些調試和狀態行來自命令行。 由於我想解析文件,因此必須刪除這些行。 我的問題是:這怎么可能? 最好就位,即文件名保持不變。
謝謝你的幫助。
一種低效的解決方案是讀取全部內容並查找發生的位置:
fileName="yourfile.xml"
with open(fileName,'r+') as f:
contents=f.read()
contents=contents[contents.find("< ?xml version="1.0"? >"):]
f.seek(0)
f.write(contents)
f.truncate()
該文件現在將包含從“ <?xml version =“ 1.0”?>“開始的原始文件內容。
讀取文件時修剪文件頭該怎么辦?
import xml.etree.ElementTree as et
with open("input.xml", "rb") as inf:
# find starting point
offset = 0
for line in inf:
if line.startswith('<?xml version="1.0"'):
break
else:
offset += len(line)
# read the xml file starting at that point
inf.seek(offset)
data = et.parse(inf)
(這假定xml標頭以其自己的行開頭,但適用於我的測試文件:
<!-- This is a line of junk -->
<!-- This is another -->
<?xml version="1.0" ?>
<abc>
<def>xy</def>
<def>hi</def>
</abc>
既然您說您有幾個文件,那么使用fileinput
可能比open
更好。 然后,您可以執行以下操作:
import fileinput
import sys
prolog = '< ?xml version="1.0"? >'
reached_prolog = False
files = ['file1.xml', 'file2.xml'] # The paths of all your XML files
for line in fileinput.input(files, inplace=1):
# Decide how you want to remove the lines. Something like:
if line.startswith(prolog) and not reached_prolog:
continue
else:
reached_prolog = True
sys.stdout.write(line)
閱讀文件輸入fileinput
應該使事情更清楚。
PS:這只是快速反應; 我還沒有運行/測試代碼。
使用regexp的解決方案:
import re
import shutil
with open('myxml.xml') as ifile, open('tempfile.tmp', 'wb') as ofile:
for line in ifile:
matches = re.findall(r'< \?xml version="1\.0"\? >.+', line)
if matches:
ofile.write(matches[0])
ofile.writelines(ifile)
break
shutil.move('tempfile.tmp', 'myxml.xml')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.