Created
September 21, 2012 01:20
-
-
Save amitsaha/3759263 to your computer and use it in GitHub Desktop.
File finding Utility
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
"""myfind | |
Usage: | |
myfind.py [--directory=<dir>] [--pattern=<p>] [--text=<text>] | |
myfind.py -h | --help | |
myfind.py --version | |
Examples: | |
myfind.py | |
lists all files in the current directory | |
myfind.py --directory='/home/gene' --pattern='*.py' | |
lists all .py files in /home/gene | |
myfind.py --directory='/home/gene' --pattern='*.py' --text='spam'' | |
lists all .py files in /home/gene containing the text spam | |
Options: | |
-h --help Show this screen. | |
--directory=<dir> Directory to start searching (default: .) | |
--pattern=<p> Files to look for (default: *.*) | |
--text=<text> Text to search for (default: 'None') | |
""" | |
from docopt import docopt | |
import os | |
import fnmatch | |
# do the walk | |
def walk(starthere, lookfor): | |
for (root, dirs, files) in os.walk(starthere,followlinks=True): | |
for fname in files: | |
if fnmatch.fnmatch(fname,lookfor): | |
yield(os.path.realpath(os.path.join(root,fname))) | |
if __name__ == '__main__': | |
arguments = docopt(__doc__, version='myfind v0.001') | |
if arguments['--directory']: | |
starthere = os.path.abspath(arguments['--directory']) | |
else: | |
starthere = '.' | |
if arguments['--pattern']: | |
lookfor = arguments['--pattern'] | |
else: | |
lookfor = '*' | |
if arguments['--text']: | |
text = arguments['--text'] | |
else: | |
text = None | |
for filename in walk(starthere,lookfor): | |
if text is not None: | |
try: | |
with open(filename,'r') as f: | |
if text in f.read(): | |
print filename | |
except IOError: | |
# permission/link followup failure, etc | |
pass | |
else: | |
print filename |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There was a problem with the formatting of the previous comment,
the second example should read:
myfind.py --directory='/home/gene' --pattern='_.py' --> ls _.py