2

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?

Philip McQuitty
  • 1,077
  • 9
  • 25
  • 36
  • possible duplicate of [Using global variables in a function other than the one that created them](http://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them) – Lukas Graf Oct 26 '14 at 02:21

2 Answers2

4

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
bakkal
  • 54,350
  • 12
  • 131
  • 107
  • Python has now recognized it properly, but when I read fn in btnHDI, it is not returning a string like it would have up in my mnuRead function. Not sure why? – Philip McQuitty Oct 26 '14 at 02:42
1

You need to put fn both out and in the function

fn = 2

def func():
    global fn

You can read a global within a function but you cannot change it; python will automatically make it local unless you use global in front of the variable when you try and change it in the function.

Better to:

fn = func():
    return value to fn

unless you absolutely need it

Remy J
  • 709
  • 1
  • 7
  • 18