简体   繁体   English

在不编写新文件的情况下修改Python文件对象

[英]Modifying a Python file object without writing a new file

I'd like to be able to add a line at the beginning and a line at the end of an xml file object, and then parse the object with ElementTree. 我希望能够在xml文件对象的开头和结尾添加一行,然后用ElementTree解析该对象。

I could read the file, then write the file back out with the new lines, then read it back in and parse it, but it seems dumb to reread the file. 我可以读取文件,然后用新的行写回文件,然后读回并解析它,但是重新读取文件似乎很愚蠢。

Isn't it possible to modify this file object in place? 是否可以就地修改此文件对象?

Did you notice that ElementTree.ElementTree has also a fromstring() method ? 您是否注意到ElementTree.ElementTree还具有fromstring()方法?

lines = open("/path/to/file.xml").readlines()
lines.insert(0, "<something>")
lines.append("</something>")
xml = "".join(lines)
tree = ElementTree.fromstring(xml)

Or (more efficient on big files - thanks to chepner): 或者(在大文件上效率更高-感谢chepner):

with open("/path/to/file.xml") as source: 
    xml = "".join(itertools.chain(["<something>"], source, ["</something>"]))
# etc...   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM