smartel99

file search

Jun 26th, 2018
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.03 KB | None | 0 0
  1. import os
  2. import glob
  3. import platform
  4. import collections
  5.  
  6. SearchResult = collections.namedtuple('SearchResult', 'file, line, text')
  7.  
  8. def main():
  9.     print_header()
  10.     folder = get_folder_from_user()
  11.     if not folder:
  12.         print("Sorry, we can't search that location.")
  13.         return
  14.  
  15.     text = get_search_text_from_user()
  16.     if not text:
  17.         print("We can't search for nothing!")
  18.         return
  19.  
  20.     matches = search_folders(folder, text)
  21.     print('----- MATCH -----')
  22.     for m in matches:
  23.         print('file: ' + m.file)
  24.         print('line: {}'.format(m.line))
  25.         print('match: ' + m.text.strip())
  26.         print()
  27.  
  28.  
  29. def print_header():
  30.     print('-------------------------')
  31.     print('     FILE SEARCH APP')
  32.     print('-------------------------')
  33.     print()
  34.  
  35.  
  36. def get_folder_from_user():
  37.     folder = input('What folder do you want to search? ')
  38.     if not folder or not folder.strip():
  39.         return None
  40.  
  41.     if not os.path.isdir(folder):
  42.         return None
  43.  
  44.     return os.path.abspath(folder)
  45.  
  46.  
  47. def get_search_text_from_user():
  48.     text = input('What are you searching for [single phrase only]?')
  49.     return text.lower()
  50.  
  51.  
  52. def search_folders(folder, text):
  53.  
  54.     all_matches = []
  55.     if(platform.system() == 'Darwin'):
  56.         glob.glob(os.path.join(folder, '*'))
  57.     else:
  58.         items = os.listdir(folder)
  59.  
  60.     for item in items:
  61.         full_item = os.path.join(folder, item)
  62.         if os.path.isdir(full_item):                  # Si c'est un folder
  63.             yield from search_folders(full_item, text) # Cherche dans ce folder
  64.            
  65.         else:
  66.             yield from search_file(full_item, text)
  67.  
  68.  
  69. def search_file(filename, search_text):
  70.     with open(filename, 'r', encoding='utf-8') as fin:
  71.         line_num = 0
  72.         for line in fin:
  73.             line_num += 1
  74.             if line.lower().find(search_text) >= 0:
  75.                 m = SearchResult(line=line_num, file=filename, text=line)
  76.                 yield m
  77.  
  78.  
  79. if __name__ == '__main__':
  80.     main()
Advertisement
Add Comment
Please, Sign In to add comment