Chapter 17: Miscellaneous and Advanced Features

Program 17.1, Page number: 382

In [1]:
import sys

def main():
    
        #Un-Comment this while execution from terminal/Command Line
        #if(len(sys.argv)!=3):
                #print("need two file names!")
                #sys.exit()
       
        inName="source.txt"                 #str(sys.argv[1])
        outName="target.txt"                #str(sys.argv[2])

        #Try to open a file for reading
        try:
            inn=open(inName,"r")         
        except:# Exception:
                print("cant open {0} for reading".format(inName))
                sys.exit()

        try:
               out=open(outName,"w") 
        except:# Exception:
                print("cant open {0} for writing".format(outName))
                sys.exit()

        string=inn.read()               #Read content from File-1
        out.write(string)               #Write content to File-2

        inn.close()
        out.close()


        print("File has been copied.\n");


if  __name__=='__main__':
        main()
An exception has occurred, use %tb to see the full traceback.

SystemExit
cant open source.txt for reading
To exit: use 'exit', 'quit', or Ctrl-D.