I have a file I open, I then put the contents of this file into a list. I then split the list at "\r" and output this to a textctrl. the problem lies that my list.txt is 4 lines long, but when i open this in my program, it goes from 4 lines to 10, and duplicates some of the text. no idea where i'm going wrong.
example of my list.txt
A
B
C
D
what my program writes to the textctrl multiline box
A
A
B
A
B
C
A
B
C
D
I'm fairly new to python and wxpython, so to me, my code looks OK, and I cannot see where it's duplicating it.
def OnOpen(self,e):
dlg = wx.FileDialog(self, "Choose a file to open", self.dirname, "", "*.*", wx.OPEN) #open the dialog boxto open file
if dlg.ShowModal() == wx.ID_OK: #if positive button selected....
directory, filename = dlg.GetDirectory(), dlg.GetFilename()
self.filePath = '/'.join((directory, filename))
f = open(os.path.join(directory, filename), 'r') #traverse the file directory and find filename in the OS
self.myList = []
for line in f:
self.myList.append(line)
for i in (self.myList):
for j in i.split("\r"):
self.urlFld.AppendText(j)
self.fileTxt.SetValue(self.filePath)
f.close
dlg.Destroy()
2 Answers 2
wait, i got it, my indentation was wrong!! such a silly thing!
solved :)
new code:
def OnOpen(self,e):
dlg = wx.FileDialog(self, "Choose a file to open", self.dirname, "", "*.*", wx.OPEN) #open the dialog boxto open file
if dlg.ShowModal() == wx.ID_OK: #if positive button selected....
directory, filename = dlg.GetDirectory(), dlg.GetFilename()
self.filePath = '/'.join((directory, filename))
f = open(os.path.join(directory, filename), 'r') #traverse the file directory and find filename in the OS
self.myList = []
for line in f:
self.myList.append(line)
for i in (self.myList):
for j in i.split("\r"):
self.urlFld.AppendText(j)
self.fileTxt.SetValue(self.filePath)
f.close
dlg.Destroy()
1 Comment
with statement). Also why not iterate through the lines, adding to self.mylist and for j in i.split("\r"): self.urlFld.AppendText(j) at the same time?Use 'with' to open the FileDialog then it will get destroyed when finished with.
Let the control load the file itself using the method 'LoadFile', then you dont need to worry about opening/closing the file yourself.
Use the control's method 'GetValue()' and split the result to create the list.
def OnOpen(self,e):
with wx.FileDialog(self, "Choose a file to open", self.dirname,
"", "*.*", wx.OPEN) as dlg:
if dlg.ShowModal() == wx.ID_OK:
directory, filename = dlg.GetDirectory(), dlg.GetFilename()
self.filePath = '/'.join((directory, filename))
self.urlFld.LoadFile(self.filePath)
self.myList = self.urlFld.GetValue().split('\n')
f.closedoes not actually call the function.