-3

Below is a simple program of reading a file and reading how many 8s there are in the file:

import sys

if len(sys.argv) == 1:
  print "ERROR: Please put a filename after your Python file!"

else:
  myFile = sys.argv[1] 
  new = open(myFile)
  numEight = 0
  text = new.read()
  line = len(text.splitlines())



for char in text:
  if char == "8":
    numEight = numEight + 1

print "There are ", numEight, "in this text file"

Question is, how do you create a try catch if the filename entered is not correct? or, is there a way to do that in an elif statement?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • 5
    Many tutorials out there. Why not reading them? – Julien Sep 19 '17 at 01:05
  • 2
    Possible duplicate of [How do I check whether a file exists using Python?](https://stackoverflow.com/questions/82831/how-do-i-check-whether-a-file-exists-using-python) – OneCricketeer Sep 19 '17 at 01:11

1 Answers1

0

In a try/except statement, the code that may fail goes in the try part meanwhile the code that should run if an exception occurs goes in the except part.

try:
    myfile = open(filename)
except IOError as E:
    print 'File Not Found'
Henry
  • 362
  • 2
  • 8