【发布时间】: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()
【问题讨论】:
-
因未提供完整回溯而被否决。您应该知道 3000 的声誉。尤其是因为您没有正确缩进代码。
-
回溯会很好,行号真的很有帮助。
-
在第一次赋值'f'之前,try块中显然发生了错误。
标签: python multithreading