I'm trying to program a wxFormBuilder interface to write text from a wxListBox into a text file. My current code:
def clickSave (self, parent):
dialog = wx.FileDialog(None, "Choose a file", os.getcwd(), "", "*.*", wx.SAVE)
if dialog.ShowModal() == wx.ID_OK:
fn = dialog.GetPath()
fh = open(fn, "w")
for i in range(self.m_listBox4.GetCount()):
listBox = self.m_listBox4.GetString(i) + "\n"
fh.write(listBox)
fh.close()
Currently this code saves only the last entry in the listbox instead of all of the entries. I'm also having trouble importing lists from a text file into the wxListBox. With the code I have, I'm getting a "TypeError: String or Unicode type required" error:
def clickOpen(self, event):
dialog = wx.FileDialog(None, "Choose a file", os.getcwd(), "", "*.*", wx.OPEN)
if dialog.ShowModal() == wx.ID_OK:
stockinfo = []
fn = dialog.GetPath()
fh = open(fn, "r")
csv_fh = csv.reader(fh)
for row in csv_fh:
stockinfo.append(row)
fh.close()
for rows in stockinfo:
self.m_listBox4.Append(rows)
In the
for i in range(self.m_listBox4.GetCount()):
listBox = self.m_listBox4.GetString(i) + "\n"
you always overwrite the content of listBox variable, therefore only the last row stays in. You probably wanted to do:
listBox += self.m_listBox4.GetString(i) + "\n"
However, concatenating strings is very inefficient. You should be doing something like:
for i in range(self.m_listBox4.GetCount()):
fh.write(self.m_listBox4.GetString(i))
fh.write("\n")
As for the other one:
for row in csv_fh:
stockinfo.append(row)
Here, row is not a String or Unicode, but a sequence. You are just putting this sequence into a list and trying to add it to the list box later. Change
self.m_listBox4.Append(str(rows))
just to see what it does.