Smith
Smith

Reputation: 3063

Reuse a path in python

I have a code to search and open a file :

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

and it will show me the path of the file : C:\....\Desktop\test.txt

And i have another code that need to read the file that i have chose :

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

How can i copy that path and substitute it into open(.... , 'r')?

Upvotes: 0

Views: 230

Answers (2)

Matt
Matt

Reputation: 22143

Change

print filedialog.GetPath()

to

path = filedialog.GetPath()
print path

then do whatever you want with the path variable.

Upvotes: 2

PenguinCoder
PenguinCoder

Reputation: 4367

Use a variable?

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

Upvotes: 4

Related Questions