2011-02-03 36 views
0

我有一個wx.ListView框中命名lvActions,我使用類似的代碼,將數據添加到如何輸出wx.ListView箱的conents到外部的日誌文件

self.lvActions.Append([datetime.datetime.now(),filename,"Moved"]) 

我想要做的就是當我完成所有操作並獲得一個列表時,我想將此文件的全部內容輸出到日誌文件中。這是我想做到這一點

logfile = open(logFullPath, "a") 
for events in self.lvActions: 
    logfile.write(events) 
logfile.close() 

的錯誤我得到的回覆是

TypeError: 'ListView' object is not iterable 

如果一個ListView不迭代,我怎麼可以轉儲其內容到一個文件?

+0

列表是否只有一列? – 2011-02-03 22:01:00

回答

1

正如你所指出的那樣,listview本身並不是按照你喜歡的方式迭代的。與大多數wx小部件一樣,您需要計算小部件中的項目數量,然後詢問該位置的項目文本。既然你是一個列表視圖(從listctrl的派生)工作,你將獲得爲每列分別

logfile = open(logFullPath, "a") 
for event in xrange(self.lvActions.GetItemCount()): 
    date = self.lvActions.GetItem(event, 0).GetText()  # item in column 0 
    filename = self.lvActions.GetItem(event, 1).GetText() # col 1, etc 
    action = self.lvActions.GetItem(event, 2).GetText() 
    logfile.write("{0}, {1}, {2}\n".format(date, filename, action) 

logfile.close() 

的GetItem()返回表示該行/列的數據ListItem對象的文本。然後我使用GetText()方法從該項目對象中獲取文本。您應該也可以根據需要添加錯誤。另外,我使用了硬編碼的列名(根據您的輸入)。你需要適當調整這些。

+0

你可以避免使用`logfile.close()`和一些異常處理,如果你把它放在一個`with`塊中:`打開(logFullPath,「a」)作爲日誌文件:` – Velociraptors 2011-02-03 22:26:37

相關問題