I'm trying to process some files using threading in Python.Some threads work fine with no error but some through the below exception
我正在尝试处理一些在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
while running my program
在运行我的程序
Here is Python function
这是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()
Here is how i'm calling the above function through threading
下面是我如何通过线程调用上面的函数。
t = Thread(target=ProcessFile,args=(fieldType,filePath,data))
t.start()
1 个解决方案
#1
2
Obviously, you got an exception somewhere in your 'try' clause before you actually wrote anything to f. So not only does f not hold a value, it doesn't even exist.
显然,在你写任何东西到f之前,你在你的“try”子句中有一个例外,所以不仅f没有值,它甚至不存在。
Simplest fix is to add
最简单的解决方法是添加。
f = None
above the try clause. But probably, you are not expecting an exception that early, so maybe you should check the data you are sending this function
以上条款。但是很可能,您不希望在早期出现异常,所以您应该检查发送该函数的数据。
#1
2
Obviously, you got an exception somewhere in your 'try' clause before you actually wrote anything to f. So not only does f not hold a value, it doesn't even exist.
显然,在你写任何东西到f之前,你在你的“try”子句中有一个例外,所以不仅f没有值,它甚至不存在。
Simplest fix is to add
最简单的解决方法是添加。
f = None
above the try clause. But probably, you are not expecting an exception that early, so maybe you should check the data you are sending this function
以上条款。但是很可能,您不希望在早期出现异常,所以您应该检查发送该函数的数据。