hai,
i want to create a code to searcha big document in text format and sort one word say "error" and need to print that whole line ....how can i implement this simply in python

openfile = open('/home/space/Desktop/test.txt', 'r')
data=openfile.read()
words=data.split()
#print words
if "error" in data:

openfile = open('/home/space/Desktop/test.txt', 'r')
for line in openfile:
    if "error" in line:
        print(line)
        break

This reads only the first line its a big document but not searching all other lines

No it should find the first error, if you want multiple error lines printed take out break. You would probably like to implement printing the line number for those lines also with using enumerate:

from sys import argv as argv
openfile = open(argv[0], 'r')
for ln,line in enumerate(openfile):
    if "error" in line:
        print("%3i: %s" % (ln+1,line))
##        break
## this line will not print even has word error, if break uncommented
## after commeting break it does

If you want to really explore power of Python, here is advanced version of saying it Pythonic way:

## "pythonista code" for the error lines
from sys import argv ## use own code as example input
print ''.join(["%3i: %s" % (ln+1,line) for ln,line in enumerate(open(argv[0])) if 'error' in line ])
## this line is completely without errors

Edited 6 Years Ago by pyTony: n/a

This article has been dead for over six months. Start a new discussion instead.