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:

Recommended Answers

All 4 Replies

openfile = open('/home/space/Desktop/test.txt', 'r')
for line in openfile:
    if "error" in line:
        print(line)
        break
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

Just take the break out, and it will read all lines, indicating all errored ones.

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
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.