[Tutor] Finding word in file
Alan G
alan.gauld at freenet.co.uk
Wed May 18 20:51:31 CEST 2005
> I'm making a program that opens a file and tries to find the word
you specify.
> I can't get it to find the word!
What are you trying?
You could simply read through the file line by line using the string
search methods. Store the previous 2 lines then when found print the
previous two lines, the current line and then read and print the next
two lines. There are more sophisticated methods but that should do...
> One more thing, the try: IOError won't work... I type the name of a
> nonexistent file and the except won't kick in and print my error
message!
> while True:
> file_name = raw_input("Enter the full file name: ")
> f = file(file_name, 'r')
> try:
> IOError
> except:
> print "File not found. Directories are not supported"
You need to catch the error not state it.
try: f = file(....)
except IOError: print 'file not....'
If you do want to force an error to be raised you must use raise:
try: raise IOError
except IOError: print 'sure enough...'
See my tutorial topic on errors for more info.
Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list