我打开了一个文件,然后将该文件的内容放入列表中。然后我将列表拆分为“\ r”并将其输出到textctrl。 问题在于我的list.txt长4行,但是当我在我的程序中打开它时,它从4行变为10行,并复制了一些文本。 不知道我哪里出错了。
我的list.txt
的例子A
B
C
D
我的程序写入textctrl多行框
A
A
B
A
B
C
A
B
C
D
我是python和wxpython的新手,所以对我来说,我的代码看起来还不行,而且我看不到它在哪里复制它。
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()
答案 0 :(得分:1)
解决了:))
新代码:
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 :(得分:0)
使用'with'打开FileDialog,然后在完成时将被销毁。
让控件使用'LoadFile'方法加载文件本身,然后你不必担心自己打开/关闭文件。
使用控件的方法'GetValue()'并拆分结果以创建列表。
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')