Last active
December 8, 2017 13:48
-
-
Save BlogBlocks/6f42b4aea8e61778a13dcfbae23b6019 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| import os | |
| import timeit | |
| def txsearch(): | |
| # Ask to enter string to search | |
| Sstring = raw_input("Search Phrase") | |
| for fname in os.listdir('./'): | |
| # Apply file type filter | |
| if fname.endswith(".txt"): | |
| # Open file for reading | |
| fo = open(fname) | |
| # Read the first line from the file | |
| line = fo.readline() | |
| # Initialize counter for line number | |
| line_no = 1 | |
| # Loop until EOF | |
| while line != '' : | |
| index = line.find(Sstring) | |
| if ( index != -1) : | |
| # Set some parameters no lines longer than 240 characters | |
| # or less than search phrase +30 characters | |
| if len(line)< 240 and len(line)> len(Sstring)+20 : | |
| #print(fname, "[", line_no, ",", index, "] ", line) | |
| #print fname,line[1:-8]," " | |
| print fname,line_no,line | |
| # Read next line | |
| line = fo.readline() | |
| # Increment line counter | |
| line_no += 1 | |
| # Close the files | |
| fo.close() | |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Search a text file with Python.