Rub*_*ert 7 python list python-2.7
我在Python 2.7.1上,我正在尝试识别所有不包含某些文本字符串的文本文件.
该程序似乎最初工作,但每当我将文本字符串添加到文件时,它就会不断出现,就好像它不包含它一样(误报).当我检查文本文件的内容时,字符串显然存在.
我试着写的代码是
def scanFiles2(rdir,sstring,extens,start = '',cSens = False):
fList = []
for fol,fols,fils in os.walk(rdir):
fList.extend([os.path.join(rdir,fol,fil) for fil in fils if fil.endswith(extens) and fil.startswith(start)])
if fList:
for fil in fList:
rFil = open(fil)
for line in rFil:
if not cSens:
line,sstring = line.lower(), sstring.lower()
if sstring in line:
fList.remove(fil)
break
rFil.close()
if fList:
plur = 'files do' if len(fList) > 1 else 'file does'
print '\nThe following %d %s not contain "%s":\n'%(len(fList),plur,sstring)
for fil in fList:
print fil
else:
print 'No files were found that don\'t contain %(sstring)s.'%locals()
scanFiles2(rdir = r'C:\temp',sstring = '!!syn',extens = '.html', start = '#', cSens = False)
Run Code Online (Sandbox Code Playgroud)
我想代码中有一个缺陷,但我真的没有看到它.
UPDATE
该代码仍然出现了许多误报:该文件不包含搜索字符串,但被确定为不包含它.
难道文本编码是一个问题吗?我将搜索字符串U作为Unicode编码的前缀,但它没有任何区别.
Python以某种方式缓存文件内容吗?我不这么认为,但这可能在一定程度上解释了文件在纠正后仍然弹出.
某种恶意软件会引起这样的症状吗?对我来说似乎不太可能,但我有点想要解决这个问题.
fal*_*tru 12
迭代列表时修改元素会导致意外结果:
例如:
>>> lst = [1,2,4,6,3,8,0,5]
>>> for n in lst:
... if n % 2 == 0:
... lst.remove(n)
...
>>> lst
[1, 4, 3, 0, 5]
Run Code Online (Sandbox Code Playgroud)
解决方法迭代复制
>>> lst = [1,2,4,6,3,8,0,5]
>>> for n in lst[:]:
... if n % 2 == 0:
... lst.remove(n)
...
>>> lst
[1, 3, 5]
Run Code Online (Sandbox Code Playgroud)
或者,您可以附加有效的文件路径,而不是从整个文件列表中删除.
修改后的版本(附加文件不是contian sstring而不是删除):
def scanFiles2(rdir, sstring, extens, start='', cSens=False):
if not cSens:
# This only need to called once.
sstring = sstring.lower()
fList = []
for fol, fols, fils in os.walk(rdir):
for fil in fils:
if not (fil.startswith(start) and fil.endswith(extens)):
continue
fil = os.path.join(fol, fil)
with open(fil) as rFil:
for line in rFil:
if not cSens:
line = line.lower()
if sstring in line:
break
else:
fList.append(fil)
...
Run Code Online (Sandbox Code Playgroud)
list.remove需要O(n)时间,而list.append需要O(1).请参阅时间复杂性.with尽可能使用声明.