【发布时间】:2018-03-29 19:43:52
【问题描述】:
为什么 PyCharm 在下面的代码中警告我 Redeclared 'do_once' defined above without usage? (警告在第 3 行)
for filename in glob.glob(os.path.join(path, '*.'+filetype)):
with open(filename, "r", encoding="utf-8") as file:
do_once = 0
for line in file:
if 'this_text' in line:
if do_once == 0:
//do stuff
do_once = 1
//some other stuff because of 'this text'
elif 'that_text' in line and do_once == 0:
//do stuff
do_once = 1
由于我希望它对每个文件执行一次,因此每次打开一个新文件时都使用它似乎是合适的,并且它确实像我想要的那样工作,但由于我没有研究过 python,只是通过学习一些东西做和谷歌搜索,我想知道为什么它会给我一个警告以及我应该做些什么不同的事情。
编辑: 尝试使用布尔值,但仍然收到警告:
为我重现警告的短代码:
import os
import glob
path = 'path'
for filename in glob.glob(os.path.join(path, '*.txt')):
with open(filename, "r", encoding="utf-8") as ins:
do_once = False
for line in ins:
if "this" in line:
print("this")
elif "something_else" in line and do_once == False:
do_once = True
【问题讨论】:
-
我试过了,无法重现。您使用的是什么 PyCharm 版本?请发布最少的完整代码,将其复制并粘贴到新的 PyCharm 脚本中会导致问题。
-
添加了导致警告的最小完整代码,可能是我正在使用 PyCharm 2016 v3.3,还没有时间/原因进行更新,但会尝试检查是否删除了警告.