Using Python to Interact with the Operating System Week4 Solution

Working with Log Files

Using Python to Interact with the Operating System WEEK 4 Qwiklabs Assessment Coursera  by Google. Welcome to Using Python to Interact with the Operating System. You’re joining thousands of learners currently enrolled in the course. This course is a part of Google IT Automation with Python Professional Certificate. Qwiklabs Assessment : “Working with Log Files

I’m excited to have you on my channel and look forward to your contributions to the learning community. By the end of this course:

  1. you’ll be able to manipulate files and processes on your computer’s operating system. You’ll also have learned about regular expressions a very powerful tool for processing text files
  2. you’ll get practice using the Linux command line on a virtual machine.

And, this might feel like a stretch right now, but you’ll also write a program that processes a bunch of errors in an actual log file and then generates a summary file. That’s a super useful skill for IT Specialists to know.

-:Skills you will learn:-

  • Setting up your Development Environment
  • Regular Expression (REGEX) 
  • Testing in Python 
  • Automating System Administration Tasks with Python
  • Bash Scripting

~Course Link: https://www.coursera.org/learn/python-operating-system

Qwiklabs Assessment : “Working with Log Files”

Codes:-

				
					#!/usr/bin/env python3
import sys
import os
import re


def error_search(log_file):
  error = input("What is the error? ")
  returned_errors = []
  with open(log_file, mode='r',encoding='UTF-8') as file:
    for log in  file.readlines():
      error_patterns = ["error"]
      for i in range(len(error.split(' '))):
        error_patterns.append(r"{}".format(error.split(' ')[i].lower()))
      if all(re.search(error_pattern, log.lower()) for error_pattern in error_patterns):
        returned_errors.append(log)
    file.close()
  return returned_errors


def file_output(returned_errors):
  with open(os.path.expanduser('~') + '/data/errors_found.log', 'w') as file:
    for error in returned_errors:
      file.write(error)
    file.close()
if __name__ == "__main__":
  log_file = sys.argv[1]
  returned_errors = error_search(log_file)
  file_output(returned_errors)
  sys.exit(0)
				
			

Leave a Reply

Your email address will not be published. Required fields are marked *