2014-02-24 61 views
1

我寫了這個腳本來寫入數據到一個xml文件。它正確寫入,但我想等待在xml文件中寫完,然後我將執行另一個代碼。這意味着另一個代碼依賴於xml數據寫入。等待xml文件寫入完成python

那麼如何等待在xml文件中完成寫入數據。

import xml.etree.ElementTree as ET 
tree = ET.parse('output.xml') 
root = tree.getroot() 
for country in root('country'): 
    root.attrib['value']=data 
tree.write('output.xml') 

上面的代碼是示例代碼和data可以在更多量,所以它需要一定的時間來寫。有些身體讓我知道該怎麼做。

+0

如果你有更多的數據,那麼它需要時間來寫,但你可以用'with'寫文件,它會採取關閉文件的關懷和過程完成。 http://docs.python.org/2/reference/compound_stmts.html#the-with-statement – Nilesh

+0

@Lafada我用'with'試過,但同樣的問題,它不等待完成在xml文件中編寫。如果你有另一個想法 – Amit

+0

'''tree.write'將等待處理完成。我不認爲它會執行下一個語句,直到'tree.write'完成它的工作。 – Nilesh

回答

2

Python File write() Method狀態

The method write() writes a string str to the file. There is no return value. Due to buffering, the string may not actually show up in the file until the flush() or close() method is called.

因此,如果你不想關閉文件的寫操作後(以便其他功能都可以打開並閱讀),你可以把

tree.flush() # does not work because no flush method in ElementTree 

後立即寫。

我看到手冊顯示寫明確寫入文件名稱而不是文件描述符。但是,這似乎是在交互模式下完成的。

如果腳本可以處理文件描述符,那麼文件描述符上的flush()或close()方法將會很有用。

其他地方顯示的示例給出了使用文件描述符寫入文件的示例。這將打開和關閉文件以及允許刷新。具體方法是留給你(:-)

text = ET.tostring(reply) 
self.wfile.write(text) 
+0

這是錯誤'AttributeError:'ElementTree'對象沒有'flush''屬性 – Amit

+0

看着代碼,也許如果你明確地打開文件並在文件描述符而不是樹上執行刷新,它可能工作。 – sabbahillel