Advertisement
ThaWade

new_parser.py

Jan 15th, 2017
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.19 KB | None | 0 0
  1. #prints to console and creates and writes to a seperate file.
  2.  
  3. import re
  4. user_input = input("What would you like to search for?\n")
  5. err_occur = [] # The list where we will store results.
  6. pattern = re.compile(user_input, re.IGNORECASE) # Compile a case-insensitive regex pattern.
  7. try: # Try to:
  8.     date_time = input("Date and time of the file?\n")
  9.     with open ('output_log__{}.txt'.format(date_time), 'rt') as in_file: # open file for reading text.
  10.         with open(user_input+'_'+date_time+'.txt', 'w') as wf: # Creates a file to write to using user input from above
  11.             for linenum, line in enumerate(in_file): # Iterate on file per line, keeping track of line numbers.
  12.                 if pattern.search(line) != None: # If substring search finds a match,
  13.                     err_occur.append((linenum, line.rstrip('\n'))) # strip linebreaks, store line and line number in list as tuple.
  14.                     for linenum, line in err_occur: # Iterate over the list of tuples, and
  15.                         print("Line ", linenum, ": ", line, sep='') # print results as "Line [linenum]: [line]".
  16.                         wf.write(line+"\n")
  17. except FileNotFoundError: # If log file not found,
  18.     print("Log file not found.") # print an error message.
  19.     print("year-month-day__hour-minute-second")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement