Yashwanth Nataraj
Yashwanth Nataraj

Reputation: 193

whats wrong in below code for searching a word in a file and writing that too another file?

I am unable to find whats wrong in this code. It is not creating new file i.e., FinalResult.txt.

import os

log = open('C:\\Sanity_Automation\\Work_Project\\Output\\Result.doc','r')
log_read=log.readlines()
x="FAIL"
if x in log_read:
    with open('C:\\Sanity_Automation\\Work_Project\\Output\\FinalResult.txt', 'w') as fout:
        fout.write("\n")
        fout.write(x)

One more thing. When it finds that word, it should write complete line of text where it was found (instead of just "FAIL").

Upvotes: 0

Views: 58

Answers (5)

rajpy
rajpy

Reputation: 2476

It has not created FinalResult.txt as there may not be "FAIL" in the 'log_read'. BTW, log_read is list. you are not searching in each line in the list instead searching against whole line, which will(in most cases) fail.

Do this to write whole line in file, there is not much change.

  import os

        log = open('C:\\Sanity_Automation\\Work_Project\\Output\\Result.doc','r')
        log_read=log.readlines()
        x="FAIL"
        for line in log_read:
            if x in line:
                with open('C:\\Sanity_Automation\\Work_Project\\Output\\FinalResult.txt', 'w') as fout:
                    fout.write("\n")
                    fout.write(line)

Upvotes: 0

pranshus
pranshus

Reputation: 187

Well you have defined X= 'Fail'. If you write x then only Fail will be written.

You should do

for line in log_read:
    if x in line : fout.write('%s\n'%line)

Moreover open the output handle only once (before the loop). Or get all writable lines first and then write once (for efficiency)

result = []
for line in log_read:
    if x in line: result.append(line)
if result: fout.write('\n'.join(result))

Upvotes: 0

Eloims
Eloims

Reputation: 5224

Also, you are reading for a ".doc" file, which i suppose is a Microsoft Word file.

You should consider converting this to a flat text file

Upvotes: 0

TerryA
TerryA

Reputation: 59984

log_read is a list of each line in the file. I think what you wanted to do was see if a word existed in the whole file instead of the word being one line.

for line in log_read:
    if x in line:
        with open('C:\\Sanity_Automation\\Work_Project\\Output\\FinalResult.txt', 'w') as fout:
            fout.write('\n')
            fout.write(line) # Writes the line to the file as well

Upvotes: 0

sapi
sapi

Reputation: 10224

log_read is a list (as the result of .readlines).

If you test x in log_read, you're asking if any item in the list is equal to FAIL. In other words, any entire line.

Do you mean the following?

for line in log_read:
   if x in line:
      # found it

Upvotes: 3

Related Questions