![](/img/trans.png)
[英]How can I save a matrix in a txt file and then open it again as a matrix in python?
[英]Can I use python to open an XML file, format it, then save it again?
您好 Python 開發人員,
我想編寫一個 python 腳本,它將在目錄中搜索任何擴展名為“.err”的文件,然后格式化文件(這是 XML 格式),然后用正確的格式覆蓋文件。 這是我到目前為止的代碼:
import xml.dom.minidom
import glob
import os
path = "/qond/apps/tomcat_qx/webapps/qxiqonddb/qxtendQueues/qdocqueue/responses/"
os.chdir(path)
for file in glob.glob("*.err"):
with open(path + file) as f:
xml_data = f.read()
xml = xml.dom.minidom.parse(xml_data)
xml_formatted = dom.toprettyxml()
f.write(xml_formatted)
f.close()
提前謝謝了!
編輯:我在上面的代碼中面臨的當前問題是:
Traceback (most recent call last):
File "qxtend_formatter.py", line 12, in <module>
xml = xml.dom.minidom.parse(xml_data)
File "/usr/lib64/python2.6/xml/dom/minidom.py", line 1918, in parse
return expatbuilder.parse(file)
File "/usr/lib64/python2.6/xml/dom/expatbuilder.py", line 922, in parse
fp = open(file, 'rb')
IOError: [Errno 36] File name too long: '<?xml version="1.0" encoding="UTF-8"?>\n<soapenv:Envelope xmlns:soapenv="http://schemas.xm.....
似乎它試圖將文件名保存為文件內容,但我希望它保留任何文件名。
我通過做兩件事解決了這個問題:
我的代碼現在看起來像這樣:
from xml.dom import minidom
import glob
import os
path = "/qond/apps/tomcat_qx/webapps/qxiqonddb/qxtendQueues/qdocqueue/responses/"
os.chdir(path)
for file in glob.glob("*.err"):
with open(file, "r") as f:
xml_data = f.read()
doc = minidom.parseString(xml_data)
with open(file, "w") as fl:
fl.write(doc.toprettyxml(indent=" ", newl="\n"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.