为什么当我尝试引用我以前在Python中定义的文件变量时会出现NameError?

2024-05-14 15:09:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图写入一个.txt文件,但我得到了错误

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

我已经在中定义了“outfile”:

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

试图写入文件“lap\u timings\u And”_时间.txt'在以下代码中:

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

我是Python的初学者,不知道为什么会发生错误。非常感谢您的帮助!你知道吗


Tags: 文件selftxttime错误outfilewritelap
1条回答
网友
1楼 · 发布于 2024-05-14 15:09:30
outfile.write(timenow + str(tempo)+ "\n")

这应该是:

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

您还需要将构造函数(__init__)的最后两行更改为:

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

更新:根据评论做一点解释。。。你知道吗

你所遇到的是“范围界定问题”。(见:Scoping and Namespaces)。你知道吗

通常,引用对象的属性需要“显式”引用。你知道吗

即:

class Foo(object):

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

    def foo(self):
        return self.my_attr

不能通过表达式return my_attr引用my_attr,因为my_attr既不在Foo.foo()范围内,也不在模块范围内,甚至不声明为全局。你知道吗

相关问题 更多 >

    热门问题