file bug???

hokieghal99 hokiegal99 at hotmail.com
Fri Nov 21 11:57:41 EST 2003


I see. I understand now. Thank you for the advice.

Bengt Richter wrote:
> On Thu, 20 Nov 2003 22:52:40 -0500, hokiegal99 <hokiegal99 at hotmail.com> wrote:
> 
> 
>>When I use 'file' instead of 'open' on the 4th line of this script (the 
>>line that begins with "outputFile") I get this error: 
>>"UnboundLocalError: local variable 'file' referenced before assignment" 
>>'open' works w/o problem and 'file' works in some other scripts that are 
>>almost identical to this one... any ideas? I can post a script where 
>>'file' works if anyone is interested.
> 
> 
> No, UIAM this is a good lesson on why it's not a good idea to use names of builtins as
> variable names.
> 
>>import os, string
>>setpath = raw_input("Enter the path to the Mac files and folders: ")
>>def clean_spaces(setpath):
>>   outputFile = open('fix-spaces.txt', 'w')
> 
>                   ^^^^-- file would be fine here if you didn't shadow the name below
> 
>>   for root, dirs, files in os.walk(setpath):
>>       for dir in dirs:
>>           old_dname = dir
>>           new_dname = old_dname.strip()
>>           if new_dname != old_dname:
>>               newpath = os.path.join(root,new_dname)
>>               oldpath = os.path.join(root,old_dname)
>>               print >> outputFile, "Replaced   ", old_dname, "\nWith 
>>      ", new_dname
>>               os.rename(oldpath,newpath)
>>       for file in files:
> 
>              ^^^^ this is effectively an assignment in the local scope, so the compiler
>                   thinks 'file' is a local variable (which it actually becomes because of this).
>                   That means that 'file' in the place of 'open' above can't be referring
>                   to the intended builtin, and so it looks like it's referring to the 'file'
>                   variable you assign here, but before it's assigned.
>                   Try using a different name, e.g.,
>          for a_file in files:
> 
>>           old_fname = file
> 
>              old_fname = a_file
> 
>>           new_fname = old_fname.strip()
>>           if new_fname != old_fname:
>>               newpath = os.path.join(root,new_fname)
>>               oldpath = os.path.join(root,old_fname)
>>               print >> outputFile, "Replaced   ", old_fname, "\nWith 
>>      ", new_fname
>>               os.rename(oldpath,newpath)
>>   outputFile.close()
>>clean_spaces(setpath)
>>
> 
> 
> Regards,
> Bengt Richter





More information about the Python-list mailing list