Class 4
see examples
#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
#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')
#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..'
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.."
output.txt
errors.txt
Total sum = 23369
'AAA'
'BBB'
'JDG474'
'TFF941'
'281'
'ZZZZ'
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))