定义了一个创建文件的函数如下:
-
def creatFile(filename):
-
-
if os.path.isfile(filename):
-
os.remove(filename)
-
else:
-
try:
-
f = open(filename,'w')
-
f.write('suijiziduan')
-
except IOError,e:
-
print 'IOError',e
-
add_log('创建文件异常')
-
finally:
-
f.close
-
add_log('成功创建文件')
反复的调用该函数:
-
createFile(file1)
-
os.remove(file1)
-
-
createFile(file1)
-
os.remove(file1)
执行该脚本,报UnboundLocalError: local variable 'f' referenced before assignment错误,google发现是因为"f"作为一个变量在两个createFile函数都调用了,在第2个createFile函数时出错,把f定义成全局变量(在createFile函数里添加global f),错误解决:
-
def creatFile(filename):
-
global f
-
if os.path.isfile(filename):
-
os.remove(filename)
-
else:
-
try:
-
f = open(filename,'w')
-
f.write('suijiziduan')
-
except IOError,e:
-
print 'IOError',e
-
add_log('创建文件异常')
-
finally:
-
f.close
-
add_log('成功创建文件')
阅读(11619) | 评论(0) | 转发(0) |