2013-04-16 2 views
0

나는 파일을 열었습니다. 그런 다음이 파일의 내용을 목록에 넣었습니다. 그런 다음 목록을 "\ r"으로 분할하고이를 textctrl로 출력합니다. 문제는 내 list.txt 길이가 4 줄이지만, 내 프로그램에서 이것을 열면 4 줄에서 10 줄로 바뀌어 일부 텍스트가 중복됩니다. 내가 어디로 잘못 가고 있는지 알지 못합니다. 내 List.txt 파일 내 프로그램이 textctrl의 여러 상자파이썬 이상한 배열 출력

A 
A 
B 
A 
B 
C 
A 
B 
C 
D 

내가, 파이썬과 wxPython을 상당히 새로 온 사람에 쓰는 것을

A 
B 
C 
D 

을의

예를 들어 내 코드의 외모, 내게 너무 알았어, 어디서 복제했는지 알 수가 없어.

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

코딩 스타일, 명명 규칙 등은 상당히 변칙적입니다. 구글 파이썬 코딩 스타일. – mtahmed

+0

Heh, 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'와'forj : 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')