Python Programming

Class 4

Error handling (Try/except)  

  • If the error is not caught then the program stops.
    • There are times when we want to prevent the program from stopping either because we know how to fix the error or we know what to do in such case.
see examples

Reading files

#Read text 
f = open('../Dropbox/helloworld.txt','r')
message = f.read()
print(message)
f.close()

#Read lines
f = open('../Dropbox/helloworld.txt','r')
message = f.readlines() #List
print(message)
f.close()

#Without closing 
with open('../Dropbox/helloworld.txt','r') as f: 
    message = f.readlines() #List

Writing files

#Example with write
file = open('../Dropbox/testfile.txt','w') 
file.write('Linea 1\n')
file.write('Linea 2\n') 
file.close() 

#re-write 
file = open('../Dropbox/testfile.txt','w') 
file.write('Linea 3\n') 
file.close() 

#append
file = open('../Dropbox/testfile.txt','a') 
file.write('Linea 4\n') 
file.close() 

#with
with open('../Dropbox/testfile.txt','a') as f:
    f.write('Linea 5\n')

Exercise 1

  • Create a function that divides two integer numbers.
    • function could handle division by zero error (ZeroDivisionError) and unsupported operand type(s) (TypeError).

 

#Test cases 

>>> divide(8, 4)
>>> 2

>>> divide(8, 4.0)
>>> 2.0

>>> divide(8, "J")
>>> 'Input not a number, try again..'

>>> divide(8, 0)
>>> 'Division by zero, try again..'

Answer 1

def divide(x, y):
    try:
    	result = x / y
    	return result
    except ZeroDivisionError:
    	return "Division by zero, try again.."
    except TypeError:
    	return "Input not a number, try again.."

Exercise 2

  1.  Create a script that reads input.txt file.
    • file contains a number in each line. 
  2. Sum all numbers and write the result in file output.txt
  3. Write lines with characters different that numbers in an file errors.txt 

 

output.txt

 

errors.txt

Total sum = 23369
'AAA'
'BBB'
'JDG474'
'TFF941'
'281'
'ZZZZ'

Answer 2

suma = 0 
with open('../Dropbox/input.txt') as f:  
    for line in f:
        try:
            suma=suma+int(line)
        except ValueError: 
            with open('../Dropbox/errors.txt','a') as f: 
                f.write(line)
    with open('../Dropbox/output.txt','w') as f: 
        f.write('Total sum = '+ str(suma))
    

Python-Programming [Class 4]

By Jose Arrieta

Python-Programming [Class 4]

Error handling, Read/Write files

  • 1,811