Demo Programs
Program 1
# readfile.py
# D. Thiebaut
# opens a file and display its contents
def main():
# open file, read contents into variable text
filename = raw_input( "file? " )
file = open( filename, 'r' )
text = file.read()
file.close()
# print each line preceded with a line counter
lines = text.split( "\n" )
count = 1
for line in lines:
print count, line
count += 1
main()
Program 2
# findInFile.py
# D. Thiebaut
# prompt user for a file name and a pattern to
# search for, then displays all the lines containing
# the pattern
def main():
# get file name and pattern to search for.
filename = raw_input( "file? " )
key = raw_input( "search for? " )
# read contents of file into variable text
file = open( filename, 'r' )
text = file.read()
file.close()
# look for pattern in each line. Print each line
lines = text.split( "\n" )
count = 1
for line in lines:
if line.find( key ) != -1:
print count, line
count += 1
main()