【问题标题】:Python Error :UnboundLocalError: local variable 'f' referenced before assignmentPython 错误:UnboundLocalError:赋值前引用了局部变量“f”
【发布时间】:2013-10-20 13:37:24
【问题描述】:

我正在尝试使用 Python 中的线程处理一些文件。一些线程工作正常,没有错误,但一些通过以下异常

Exception in thread Thread-27484:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 504, in run
    self.__target(*self.__args, **self.__kwargs)
  File "script.py", line 62, in ProcessFile
    if f is not None:
UnboundLocalError: local variable 'f' referenced before assignment

在运行我的程序时

这里是 Python 函数

def ProcessFile(fieldType,filePath,data):
    try:
        if fieldType == 'email':
            fname = 'email.txt'
        else:
            fname = 'address.txt'
        f1 = open(fname,'wb')
        for r in data[1:]:
            r[1] = randomData(fieldType)
            f1.write(r[1])
        f1.close()

        f = open(filePath,'wb')

        writer = csv.writer(f)
        writer.writerows(data)
        f.close()
        try:
            shutil.move(filePath,processedFileDirectory)
        except:
            if not os.path.exists(fileAlreadyExistDirectory):
                os.makedirs(fileAlreadyExistDirectory)
            shutil.move(filePath,fileAlreadyExistDirectory)
    finally:
        if f is not None:
            f.close()

这是我通过线程调用上述函数的方式

t = Thread(target=ProcessFile,args=(fieldType,filePath,data))
        t.start()

【问题讨论】:

标签: python multithreading


【解决方案1】:

很明显,在您真正向 f 写入任何内容之前,您的“try”子句中的某个地方出现了异常。所以 f 不仅没有值,甚至不存在。

最简单的解决方法是添加

f = None

在 try 子句之上。但很可能,您并没有那么早期待异常,所以也许您应该检查您发送此函数的数据

【讨论】:

  • 我不认为这是一个修复,解决方法是更准确地描述你写的内容。
猜你喜欢
  • 2019-11-03
  • 2015-06-14
  • 2018-06-29
  • 1970-01-01
  • 1970-01-01
  • 2017-11-11
  • 1970-01-01
  • 2012-11-14
  • 2013-11-29
相关资源
最近更新 更多