2012-05-31 31 views
0

我有一個代碼,以搜索和打開文件:重用Python中的路徑

def OpenButton(self, event): 
    filedialog = wx.FileDialog(self, message = 'Open text file', 
     defaultDir = '.', 
     defaultFile = 'TestTOC.txt', 
     wildcard = "Text source (*.txt)|*.txt|" "All files (*.*)|*.*", 
     style = wx.OPEN) 
    if filedialog.ShowModal() == wx.ID_OK: 
     print filedialog.GetPath() 
    event.Skip() 

,它會告訴我該文件的路徑:C:\....\Desktop\test.txt

,我有需要另一個代碼讀取我選擇的文件:

def ReadButton(self, event): 
    file=open('C:....\Desktop\test.txt','r') # the same path as above 
    text=file.read() 
    file.close() 

如何複製該路徑並將其替換爲開放(....,'r')?

+0

你可以讓這個路徑成爲全球嗎? –

+0

我不知道爲什麼,我不能。 – Smith

回答

4

使用變量?

def OpenButton(self, event): 
     filedialog = wx.FileDialog(self, message = 'Open text file', 
      defaultDir = '.', 
      defaultFile = 'TestTOC.txt', 
      wildcard = "Text source (*.txt)|*.txt|" "All files (*.*)|*.*", 
      style = wx.OPEN) 
     if filedialog.ShowModal() == wx.ID_OK: 
      self.filepath = filedialog.GetPath() 
     event.Skip() 

    def ReadButton(self, event): 
     file=open(self.filepath,'r') # the same path as above 
     text=file.read() 
     file.close() 
+0

非常感謝老兄! – Smith

2

變化

print filedialog.GetPath() 

path = filedialog.GetPath() 
print path 

然後做任何你想要的路徑變量。

+0

非常感謝! – Smith