2013-10-20 68 views
0

我试图来处理Python.Some线程使用线程的一些文件之前引用局部变量“F”工作正常,没有错误,但有些是通过以下例外Python的错误:UnboundLocalError:分配

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() 
+0

Downvoted无法提供完整的回溯。你应该知道更好的声誉为3000.特别是因为你没有正确缩进你的代码。 –

+0

追溯会很好,行号可以真正帮助。 –

+0

[为什么当变量有值时会得到UnboundLocalError?](http://docs.python.org/2/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the -variable-has-a-value) –

回答

2

很显然,在实际向f写入任何内容之前,在'try'子句中的某处出现异常。所以不仅f不具有价值,它甚至不存在。

简单的解决办法是增加

f = None 

try子句以上。但很可能,您并不期待这样的例外,所以也许您应该检查您发送此功能的数据。

+2

我不认为这是一个修复,解决方法它更准确地描述了你写的内容。 –

相关问题