简体   繁体   中英

Log File Parsing Python 5 2.7

I have searched through about 35 different questions that I have come across to try and resolve my issue. I am trying to search a text file for a word (or string) and write the line of that word (or string) to another file. This is what I have and I have changed it several times over the course of finding a solution. Currently, it does not write to the new file, it does create the new file, and it does not print the line where the word (string) is found it just prints () for the number of lines in the infile

x = "mama"
with open("testing.txt") as search:
     for line in search:
         line = line.rstrip()
         print()



import os

infile= 'testing.txt'
outfile= '618.txt'

source= open(infile, 'r')
target = open(outfile, 'w')
flag = 'mama'

for line in source.readlines():  #read all of the source lines into a list and iterate over
    if ('mama' in line):
        target.write(line)
        print line

The text file that it is searching are the lyrics from bohemian rhapsody. I am trying to get this to work so that I can use it on log files to find strings like "flag" and print those to a new file.

Don't open 2 files at once.

text = []
flag = 'mama'
with open(infile, "r") as readFile:
    for line in readFile.readlines()
        if flag in line:
            text.append(line)

with open(outflow, "w") as writeFile:
    for line in text:
        writeFile.write(line)

Here I open the first file and for each line in the file if 'mama' is in the line I append the line to my list text. Then I open the second file and I write each line of my list text in the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM