简体   繁体   中英

Why am I getting a NameError when I try to reference to a file variable I have previously defined in Python?

I am trying to write to a .txt file, but I get the error

File "C:\Python34\Timer.py", line 262, in Lap
outfile.write(timenow + str(tempo)+ "\n")
NameError: name 'outfile' is not defined

I have already defined 'outfile' in:

class StopWatch(Frame):  
    """ Implements a stop watch frame widget. """                                                                
    def __init__(self, parent=None, **kw):        
        Frame.__init__(self, parent, kw, bg="black")
        self._start = 0.0        
        self._elapsedtime = 0.0
        self._running = 0
        self.timestr = StringVar()
        self.lapstr = StringVar()
        self.e = 0
        self.m = 0
        self.makeWidgets()
        self.laps = []
        self.lapmod2 = 0
        self.today = time.strftime("%d %b %Y %H-%M-%S", time.localtime())
        timenow = time.strftime("%d %b %Y %H:%M:%S", time.localtime())
        outfile = open("lap_timings_and_time.txt","wt") 
        outfile.write(timenow+ "\n")

And tried to write to the file 'lap_timings_and_time.txt' in the following code:

def Lap(self):
    '''Makes a lap, only if started'''
    tempo = self._elapsedtime - self.lapmod2
    timenow = time.strftime("%d %b %Y %H:%M:%S", time.localtime())
    if self._running:
        self.laps.append(self._setLapTime(tempo))
        self.m.insert(END, self.laps[-1])
        self.m.yview_moveto(1)
        self.lapmod2 = self._elapsedtime
        outfile.write(timenow + str(tempo)+ "\n")

I'm a beginner at Python and can't figure out why the error is occurring. Any help is greatly appreciated!

outfile.write(timenow + str(tempo)+ "\n")

This should be:

self.outfile.write(timenow + str(tempo)+ "\n")

You'll also want to change the last two lines of your constructor ( __init__ ) to:

    self.outfile = open("lap_timings_and_time.txt","wt") 
    self.outfile.write(timenow+ "\n")

Update: A bit of explanation as per the comments...

What you were encountering was a "Scoping Issue". (See: Scoping and Namespaces ).

In general referencing attributes of an object requires "explicit" referenecing.

ie:

class Foo(object):

    def __init__(self):
        self.my_attr = "foo"

    def foo(self):
        return self.my_attr

You cannot reference my_attr by the expression return my_attr as my_attr is neither in Foo.foo() scope nor part of the module's scope or even declared a global.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM