Search code examples
pythonanalyticslog-analysis

How to get data from txt file in python log analysis?


I am beginner to python, I am trying to do log analysis, but I do not know how to get the txt file.

This is the code for outputting date, but these dates must be taken from the txt file :

import sys
import re

file = open ('desktop/trail.txt')

for line_string in iter(sys.stdin.readline,''):
  line = line_string.rstrip()
  date = re.search(r'date=[0-9]+\-[0-9]+\-[0-9]+', line)
  date = date.group()
  print date

Solution

  • You can use with statement to open a file safely and read each line with a readlines method. readlines returns a list of string.

    Below code should work in your case:

    import sys
    import re
    
    with open('desktop/trail.txt', 'r') as f:
        for line in f.readlines():
            line = line_string.rstrip()
            date = re.search(r'date=[0-9]+\-[0-9]+\-[0-9]+', line)
            date = date.group()
            print date