2011-07-19 84 views
4

這可能是一個真正愚蠢的問題,但我還沒有找到答案。 一旦我根據需要修改xml樹,我如何將它寫回到文件?用美麗的湯寫入xml

代碼:

workbook = open("C:\\Users\\rabdel.WINCMPT\\Documents\\Retail Footwear.twb") 
soup = BeautifulSoup(workbook) 

for dashboard in soup.findAll("dashboard"): 
    print dashboard["name"] 
    if dashboard["name"] == "S1": 
     dashboard.extract() 

for window in soup.findAll("window"): 
    print "class:",window["class"] 
    if "name" in [x[0] for x in window.attrs]: 
     print "name:",window["name"] 
     if window["name"] == "S1": 
      window.extract() 
+2

你有沒有試着寫STR(湯)到一個文件? – James

回答

11

最簡單的方法,得到輸出作爲一個字符串並寫入文件:

f = open(workbook.name, "w") 
f.write(soup.prettify()) 
f.close()