![](/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.