Created
April 15, 2019 19:33
-
-
Save pca2/0efa27e281ff2cb173e11752cebb81b1 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
#Search for files that do NOT contain a given string | |
#Import os module | |
import os | |
# Ask the user to enter string to search | |
search_path = input("Enter directory path to search : ") | |
file_type = input("File Type : ") | |
search_str = input("Enter the search string : ") | |
# Append a directory separator if not already present | |
#if not (search_path.endswith("/") or search_path.endswith("\\") ): | |
# search_path = search_path + "/" | |
# If path does not exist, set search path to current directory | |
if not os.path.exists(search_path): | |
search_path ="." | |
results = [] | |
# Repeat for each file in the directory | |
#for fname in os.listdir(path=search_path): | |
for fname in [os.path.join(dp, f) for dp, dn, fn in os.walk(os.path.expanduser(search_path)) for f in fn]: | |
# Apply file type filter | |
if fname.endswith(file_type): | |
# Open file for reading | |
fo = open(fname) | |
#Add the file to the results array | |
results.append(fname) | |
# Read the first line from the file | |
line = fo.readline() | |
# Initialize counter for line number | |
line_no = 1 | |
# Loop until EOF | |
while line != '' : | |
# Search for string in line | |
index = line.find(search_str) | |
if ( index != -1) : | |
#If a line does contain the file, remove the file from results array and move on to next file | |
results.remove(fname) | |
break | |
# Read next line | |
line = fo.readline() | |
# Increment line counter | |
line_no += 1 | |
# Close the files | |
fo.close() | |
print('Search string \"' + search_str + '\" not found in following files:') | |
print(*results,sep='\n') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment