Checkpoint 8.6.1.
Put the following code in order to open and count the lines of a file from the user. Watch out for indentation and extra code blocks!
input
as follows:fname = input('Enter the file name: ')
fhand = open(fname)
count = 0
for line in fhand:
if line.startswith('Subject:'):
count = count + 1
fhand.close()
print('There were', count, 'subject lines in', fname)
fname
and open that file. Now we can run the program repeatedly on different files.python search6.py # seach6.py is the file containing the above script. Enter the file name: mbox.txt There were 1797 subject lines in mbox.txt python search6.py Enter the file name: mbox-short.txt There were 27 subject lines in mbox-short.txt
count = 0 # Start counting from zero
fname = input('Enter the file name: ') # Close parentheses
fhand = open(fname) # Open the correct file name
for line in fhand:
if line.startswith('Received:'):
# Check at the beginning of the line, not the end
count = count + 1 # Correct indentation.
fhand.close()
print('There were', count, 'lines starting with "Received:" in the file', fname)