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

1.2k views Asked by At

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
2

There are 2 answers

0
mkocabas On BEST ANSWER

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
0
puf On

you can do something like

for line in file.readlines():

don't forget about file closing! You can do it with file.close()