0

I have a txt file called test.txt with 4 lines in it. I want to copy lines containing the word 'exception' into a new file from command line argument. I have managed this far. But I also want to exception handle this for IO error. That is if from the command line, somebody misspells the word test.txt, it will throw an exception. This is my current code. Please help! I'm a beginner. Presently, if I misspell it intentionally, it is not showing the error message I intend it to show.

import sys


def Cat(filename):
     try:
      f = open(filename, 'rU')
      for line in f:
       print (line),
       return 3
     except IOError:
       print('\nIO error!!', filename)

def main():
  f1 = open(sys.argv[1])
  f2 = open(sys.argv[2], 'w')
  for line in f1:    
    if 'exception' in line:
       f2.write(line)




if __name__ == '__main__':
  main()
Ry-
  • 218,210
  • 55
  • 464
  • 476
sagarnildass
  • 31
  • 10
  • 1
    Please also fix up your indentation--all of your Python code should use the same amount of indentation for every block level, where as you're using a combination of 1, 2, and 4 spaces. 4 spaces is standard but consistency is more important (and do use more than 1 at least). – Iguananaut Dec 23 '13 at 16:32

4 Answers4

0

You need to put the open() inside a try-except block, just as you did in Cat().

Currently, you are not calling Cat(), and the open() in main() is not inside a try-except block.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

Since you said you are a beginner in Python I'll assume this a sort of "learning code". So, I won't tell you anything about the design. Also, you should do what @NPE says too.

You can try this in your main function in order to reach your goal:

def main():

    filename = open(sys.argv[1])
    if filename != "test.txt":
        raise Exception("Here goes the message error you want to show")
    f2 = open(sys.argv[2], 'w')
    for line in f1:    
        if 'exception' in line:
           f2.write(line)
Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60
0

First check if source file exists and readable -

if not (os.path.exists(file1) and os.access(file1, os.R_OK)):
   print "file1 does not exists or not readable"
   sys.exit(1)
else:
   //good to go

and then handle writing of destination file with try except block.

Arovit
  • 3,579
  • 5
  • 20
  • 24
0

You forgot to call Cat()

before

f2 = open(sys.argv[2], 'w')
Cat(f1)
for line in f1:  

and in the Cat function you will need to raise exception to stop the execution

print('\nIO error!!', filename)
raise IOError('Invalid filename')
skar
  • 401
  • 5
  • 15
  • Also, try using the ["with"](http://stackoverflow.com/questions/9282967/how-to-open-a-file-using-the-open-with-statement) statement for file opening. Ideally you want the file connections to close if an error has occurred. – skar Dec 23 '13 at 17:38