Optimize file handling in the find module (#38192)

* Optimize file handling

Use the best practice of opening and doing operations on an opened file

Signed-off-by: Daniel Andrei Minca <mandrei17@gmail.com>

* Fix docstring to Sphinx type

- update the docstrings to Sphinx type, as suggested by Toshio
- Move the pattern object assignment outside the context manager, as
  suggested by Matt

Signed-off-by: Daniel Andrei Minca <mandrei17@gmail.com>
This commit is contained in:
Daniel Andrei Mincă 2018-04-10 19:01:44 +03:00 committed by Toshio Kuratomi
parent 450cfa8776
commit 89d6c36584

View file

@ -250,19 +250,24 @@ def sizefilter(st, size):
def contentfilter(fsname, pattern): def contentfilter(fsname, pattern):
'''filter files which contain the given expression''' """
Filter files which contain the given expression
:arg fsname: Filename to scan for lines matching a pattern
:arg pattern: Pattern to look for inside of line
:rtype: bool
:returns: True if one of the lines in fsname matches the pattern. Otherwise False
"""
if pattern is None: if pattern is None:
return True return True
try: prog = re.compile(pattern)
f = open(fsname)
prog = re.compile(pattern) try:
for line in f: with open(fsname) as f:
if prog.match(line): for line in f:
f.close() if prog.match(line):
return True return True
f.close()
except: except:
pass pass