Python UnboundLocalError:局部变量';完整文件名';分配前参考
我面临的错误如下:Python UnboundLocalError:局部变量';完整文件名';分配前参考,python,python-3.x,selenium,Python,Python 3.x,Selenium,我面临的错误如下: UnboundLocalError: local variable 'fullfilename' referenced before assignment 代码块: caminho_path = self.tempDir arquivos = os.listdir(self.tempDir) for arquivo in arquivos: if arquivo.endswith(".zip"): fullfilename = os.path.jo
UnboundLocalError: local variable 'fullfilename' referenced before assignment
代码块:
caminho_path = self.tempDir
arquivos = os.listdir(self.tempDir)
for arquivo in arquivos:
if arquivo.endswith(".zip"):
fullfilename = os.path.join(caminho_path, arquivo)
self.driver.implicitly_wait(5)
sleep(10)
with ZipFile(fullfilename, 'r') as zipObj:
listOfFileNames = zipObj.namelist()
for fileName in listOfFileNames:
if fileName.endswith('.csv'):
zipObj.extract(fileName, self.tempDir)
print('unzip' + str(fileName))
for arquivo in arquivos:
if arquivo.endswith(".zip"):
fullfilename = os.path.join(caminho_path, arquivo)
错误:
File "path...", line 166, in ...
with ZipFile(fullfilename, 'r') as zipObj:
UnboundLocalError: local variable 'fullfilename' referenced before assignment
此错误消息
UnboundLocalError: local variable 'fullfilename' referenced before assignment
…意味着您已经引用了变量fullfilename
,甚至在它被赋值之前
在代码块中:
caminho_path = self.tempDir
arquivos = os.listdir(self.tempDir)
for arquivo in arquivos:
if arquivo.endswith(".zip"):
fullfilename = os.path.join(caminho_path, arquivo)
self.driver.implicitly_wait(5)
sleep(10)
with ZipFile(fullfilename, 'r') as zipObj:
listOfFileNames = zipObj.namelist()
for fileName in listOfFileNames:
if fileName.endswith('.csv'):
zipObj.extract(fileName, self.tempDir)
print('unzip' + str(fileName))
for arquivo in arquivos:
if arquivo.endswith(".zip"):
fullfilename = os.path.join(caminho_path, arquivo)
只有当条件arquivo.endswith(“.zip”)
为true
时,才会为变量fullfilename
赋值。否则变量fullfilename
将保持未分配状态
在其中一种情况下,当变量未赋值时,您尝试在代码的后面部分引用它,如下所示:
with ZipFile(fullfilename, 'r') as zipObj:
即使变量
fullfilename
仍然未赋值。因此,您会看到错误。仅当if语句为true时才设置变量,但无论if语句如何,您稍后都会尝试使用它。因此,如果is语句为false,则不会设置变量,因此当您稍后尝试使用它时,会出现错误