Python Forum

Full Version: name not defined error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
in below program, i try to zip the files under 1139 directory.

import os
import datetime
import zipfile

def zipt(folder):
 folder = os.path.abspath(folder)
 ver = 1
 while True:
  zip_f = os.path.basename(folder)+'_'+str(ver)+'.zip'
  if not os.path.exsits(zip_f):
    break
  ver += 1
print("\narchiving %s..."%(zip_f))
zip_file=zipfile.ZipFile(zip_f,'w')
for foldername,subfolders,filenames in os.walk(folder):
 print("\nadding files in the %s..."%(foldername))
 zip_file.write(foldername)
 for filename in filenames:
  new_base=os.path.basename(folder)+'_'
  if filename.startswith(new_base) and filename.endswith('.zip'):
    continue
  zip_file.write(os.path.join(foldername,filename))
 zip_file.close()
 print("\narchiving complete, {} created successfully".format(zip_f))
 
 zipt('c:\\dell\\1139')
but it runs with error :
Traceback (most recent call last):
File "C:\dell\test_zip.py", line 13, in <module>
print("\narchiving %s..."%(zip_f))
NameError: name 'zip_f' is not defined

my zip_f is defined with os.path.basename(folder)+'_'+str(ver)+'.zip', why still error? thanks
it's defined and value is assigned within zipt function. It has local scope, i.e. that zip_f it's not visible outside the function. One option (not recommended) is to declare it global variable, so you can change it from within the function, i.e. changes you made in the function will have effect also outside the function. The better option is to return the value from the function and assign it to a variable zip_f. In both cases it will not work till you actually call and execute the function, which you do in the last line. i.e. you will need to move that line before you are able to use zip_f name