简体   繁体   中英

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.

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 ?

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):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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