variable assignment within a loop

hokieghal99 hokiegal99 at hotmail.com
Mon Nov 3 15:37:28 EST 2003


I have this for loop in a program that I'm writing:

         for bad_dir_char in bad_dir_chars:
             newdir = dir.replace(bad_dir_char,'-')

Now, when I use this if statement:

         if newdir != dir:
             old_dir_path = os.path.join(root,dir)
             new_dir_path = os.path.join(root,newdir)
             os.rename(old_dir_path,new_dir_path)
             print "replaced:	",bad_dir_char,"

I get a "local variable 'newdir' referenced before assignment" error.

I am somewhat new to programming and I do not understand a lot about 
where variables live and where they do not. I know the difference 
between global and function specific variables, but I was under the 
impression that if a local variable lived within a function that I could 
access its contents *anywhere* in that function. This is obviuously 
wrong, could someone expound upon this? Not that it matters, but below 
is the entire function that I'm playing with. I have a working version 
of it, but I'm cleaning it up a bit (I know that that is a bad thing, 
but it helps me learn more about programming).

import os, re, string
print
setpath = raw_input("Path to the Directory to act on: ")
def clean_names(setpath):
     bad = re.compile(r'%2f|%25|%20|[*?<>/\|\\]') # bad characters
     for root, dirs, files in os.walk(setpath):
         for dir in dirs:
             bad_dir_chars = bad.findall(dir)
             for bad_dir_char in bad_dir_chars:
                 newdir = dir.replace(bad_dir_char,'-')
             if newdir != dir:
                 old_dir_path = os.path.join(root,dir)
                 new_dir_path = os.path.join(root,newdir)
                 os.rename(old_dir_path,new_dir_path)
                 print "replaced:	",bad_dir_char,"	in dir		",dir," 	",





More information about the Python-list mailing list