1

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
  • Downvoted for not providing the full traceback. You should know better with a reputation of 3000. Especially because you did not indent your code properly. Commented Oct 20, 2013 at 13:40
  • Trace back would be nice, Line number can really help. Commented Oct 20, 2013 at 13:42
  • Why am I getting an UnboundLocalError when the variable has a value? Commented Oct 20, 2013 at 13:46
  • Obviously an error occurs in the try block before you assign 'f' for the first time. Commented Oct 20, 2013 at 13:53

1 Answer 1

3

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.

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

Sign up to request clarification or add additional context in comments.

1 Comment

I don't think it's a fix, workaround it's more accurate description for what you wrote.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.