0

I'm trying to process some files using threading in Python.Some threads work fine with no error but some through the below exception

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

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()
4

1 回答 1

2

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

最简单的解决方法是添加

f = None

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

于 2013-10-20T13:40:58.240 回答