0

我有一个代码来搜索和打开一个文件:

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

我如何复制该路径并将其替换为 open(.... , 'r')?

4

2 回答 2

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()  
于 2012-05-31T17:26:23.960 回答
2

改变

print filedialog.GetPath()

path = filedialog.GetPath()
print path

然后对路径变量做任何你想做的事情。

于 2012-05-31T17:26:30.867 回答