为什么在下面的代码中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,只是通过做和谷歌来学习一些东西,我想知道为什么它会给我一个警告,以及我应该做什么不同。
Edit:已尝试使用布尔值,但仍收到警告:
为我重现警告的简短代码:
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
发布于 2017-05-09 17:08:14
我的猜测是PyCharm对使用整数作为标志感到困惑,在您的用例中可以使用几种替代方案。
使用布尔标志而不是整数
file_processed = False
for line in file:
if 'this' in line and not file_processed:
# do stuff
file_processed = True
...
一种更好的方法是在处理完文件中的内容后简单地停止,例如:
for filename in [...list...]:
while open(filename) as f:
for line in f:
if 'this_text' in line:
# Do stuff
break # Break out of this for loop and go to the next file
发布于 2018-03-29 19:43:52
为了解决一般情况:
你可能正在做的事
v1 = []
for i in range(n):
v1.append([randrange(10)])
v2 = []
for i in range(n): # <<< Redeclared i without usage
v2.append([randrange(10)])
你可以做什么?
v1 = [[randrange(10)] for _ in range(5)] # use dummy variable "_"
v2 = [[randrange(10)] for _ in range(5)]
https://stackoverflow.com/questions/43865347
复制相似问题