2013-04-16 58 views
0

我有一个文件打开,然后我把这个文件的内容放入一个列表中。然后我在“\ r”分割列表并将其输出到一个textctrl。 问题在于我的list.txt长度是4行,但是当我在程序中打开它时,它从4行到10行,并复制了一些文本。 不知道我哪里错了。我LIST.TXTPython奇怪的数组输出

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() 
+1

说实话,你的编码风格,命名约定等都是相当偏离的。 Google python编码风格。 – mtahmed

+0

嘿,3个嵌套for循环可能不是理想的..你应该在你的线程中标记wxPython,如果这是你用来显示框。 – Torxed

+0

'f.close'实际上并不调用该函数。 –

回答

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

恭喜,但您并未真正关闭该文件btw。 (避免这种情况的最好方法是使用'with'语句),并且有更好的风格。另外为什么不重复遍历行,在i.split(“\ r”)中添加'self.mylist'和'for j: self.urlFld.AppendText(j)'同时? – jamylak

0

使用 '与' 打开的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')