Global variable not recognized in Python

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

What I have tried:

def mnuRead(self, event):

    global fn
    dialog = wx.FileDialog(None, "Choose a file", os.getcwd(), "", "*.*", wx.OPEN)

    if dialog.ShowModal() == wx.ID_OK:
        countrylist = []
        fn = dialog.GetPath()
        fh = open(fn, "r") 
        csv_fh = csv.reader(fh)
        for row in csv_fh:
            countrylist.append(row)
        fh.close()
        for rows in countrylist:
            self.myListCtrl.Append(rows)

def btnHDI(self, event):

    myfile = open(fn, "rb")

In my first function, I prompt the user to open a file of their choice. I have a declared, and then assigned a global variable to "fn".

When I call on "fn" in my btnHDI function, Python is saying that fn is "undefined".

What am I doing wrong? Is this not the proper use of a global variable? How can I use the file path selected by the user in my "mnuRead" function in all my other functions?

Answers

If you insist on having fn as a global, why not just have fn defined in the module:

# Somewhere in the same .py module
fn = None   

def mnuRead(self, event):
    # Modify fn

def btnHDI(self, event):
    # Read fn

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/26569184/global-variable-not-recognized-in-python

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils