Friends I need to search for some strings like 'info stat, waiting, connecting, connection pending' in the source txt file those lines which has the strings need to be extracted and saved to a new file.

import re
import os
import sys

file = open("C:\Users\Administrator\Desktop\logs test\source.txt", 'rU')
script = file.readlines() 
file.close() 
for line in script:
 re.search(r'book.info', script, re.I)

after searching how to get the lines that matches the string to a file. Thanks in advance

Recommended Answers

All 2 Replies

Adapt my code snippet to do in test for lines instead of whole file:
http://www.daniweb.com/software-development/python/code/316585

More simple finding word in file, showing lines containing word:

fname = 'alice.txt'
find = ('cat', 'queen')
with open(fname) as infile:
    for line_no, line in enumerate(infile, 1):
        lline = line.lower()
        if any(word.lower() in lline for word in find):
            print('%4i: %s' % (line_no, line.rstrip()))

BTW your original code line 5 should have r"" quotes (maybe works by chance, but what if file or directory name starts with 'n'?).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.