[Tutor] Finding word in file
Joseph Quigley
cpu.crazy at gmail.com
Wed May 18 15:19:44 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! I also would like to know how I can get
it to print 2 lines above and 2 lines below the line with the word specified.
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!
Not to mention the program is killed. How can i fix that?
Thanks,
JQ
Full Code:
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"
while True:
line = f.readline()
if len(line) == 0:
break
find_word = raw_input("What word do you want to find (quit() to
quit)?\n> ")
if find_word in file_name:
print f.readline(find_word)
elif find_word == "quit()":
break
print line,
f.close()
close = raw_input("\n\nQuit program? (Y/N)> ")
if ((close == "Y") or ("y" == close)):
break
else:
print
More information about the Tutor
mailing list