slide set 6
slide set 6
2
Output to the screen – print()
print(object(s), sep=separator, end=end,
file=file, flush=flush)
analyze_data.py
Data
2021
income.txt
To access the file 'income.txt' from the code inside 'analyze_data.py' we can use:
Absolute path: C:\Data\2021\income.txt
Relative path: ..\Data\2021\income.txt
5
File I/O in Python
• File I/O in Python enables our programs to
retrieve data from files (read), write data to
files (write) or append data to files (append)
• To access a file, we need to open it and when
we finish, we need to close it
• We will concentrate on text files (.txt)
6
Text file
7
Opening a connection to a file
8
Reading a whole file
>>> f = open('test_file.txt', 'r') # returns a file object
>>> s = f.read() # reads the entire file, returns its content as a string
>>> print(s)
'This is a file'
# in case the file is located in a different directory - use the full path
>>> f= open('C:/Users/Desktop/ta5_code/test_file.txt','r’)
>>> f
>>> f.read()
'This is a file'
>>> f.close()
9
Note about ‘\’
f=open('C:/Users/Desktop/targil/test_file.txt','r') •
Alternatives:
• 'C:/Users/Desktop/targil/test_file.txt'
• 'C:\\Users\\Desktop\\targil\\test_file.tx
t'
• r'C:\Users\Desktop\targil\test_file.txt'
10
Let’s work – Q1
• Open Notepad or Notepad++, write some text to
a new file and save the file as a text file to a
location you choose.
12
Common ways for reading
from a file
• f.read() – reads an entire file as a single string
• f.readline() – reads the next line as a string
relative to the current file position
• f.readlines() – reads all remaining lines as a
list of strings
• Iterating a file using for loop:
for line in f:
…
13
Remarks
• Read operations advance the file position.
• To start reading a file from its beginning, we can re-open it.
• Remember to close the file using f.close() to free up resources!
• In a string, '\n' represents the new line character.
14
Parsing a text file – split()
• Parsing: Reading a text file and breaking every
line to fields based on some predefined format
• The split command splits a string to tokens
using a delimiter, returns a list of strings.
s = "topeka, kansas city,wichita,,olathe"
16
Parsing a text file
• Use strip() to remove unwanted characters from
both sides of the string.
>>> ' spacious '.strip()
'spacious'
>>> 'www.example.com'.strip('comwz.')
'example'
18
Printing word frequencies
• Print the words appearing in a file sorted by decreasing
frequencies (print most frequent word first)
f = open("input.txt", "r")
d = {}
for line in f:
for word in line.split():
d[word] = d.get(word, 0) + 1
f.close()
a: 23
and: 12
where: 5
I:194
File output: writing to a file
• To write to an existing file, you must add a
parameter to the open() function:
– "a" - Append - will append to the end of the file
– "w" - Write - will overwrite any existing content
• once you opened the file in the required mode,
use f.write(str)
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
20
Example: Writing a list of
numbers to a text file
my_list = [i**2 for i in range(1,11)]
# List comprehension !
# Generates a list of squares of the numbers 1 – 10
f = open("output.txt", "w")
f.close()
21
Summary
>>> fname = 'myfile.txt'
23
Types Of Errors
• In programming we have three main types of
errors
– Syntax errors
– Runtime errors
– Semantic/logic errors
• In this lecture we deal with runtime errors
24
Exceptions
– Exceptions are run-time errors.
– A built-in mechanism for signaling problems at run-time.
– No detection before the program runs, even if the error is
“obvious”.
– Unhandled exceptions crash (stop) our programs.
Type of
Exception
25
Exceptions –More Examples
26
Handling Exceptions
We can define what happens when an exception occurs
(error handling that will occur instead of a program crash)
Wrap your code by a try-except structure.
output
before try
28
try-except – example 1
x = 5
y = 0
print('before try')
try:
print('inside try')
print(x/y)
print('exiting try')
except ZeroDivisionError:
print('exception was handled')
print('continue program')
output
before try
inside try
29
try-except – example 1
x = 5
y = 0
print('before try')
try:
print('inside try')
print(x/y) ZeroDivisionError!!!
print('exiting try')
except ZeroDivisionError:
print('exception was handled')
print('continue program')
output
before try
inside try
30
try-except – example 1
x = 5
y = 0
print('before try')
try:
print('inside try')
print(x/y)
print('exiting try')
except ZeroDivisionError:
print('exception was handled')
print('continue program')
output
before try
inside try
exception was handled
31
try-except – example 1
x = 5
y = 0
print('before try')
try:
print('inside try')
print(x/y)
print('exiting try')
except ZeroDivisionError:
print('exception was handled')
print('continue program')
output
before try
inside try
exception was handled
continue program
32
try-except Operation
33
try-except – example 2
x = 5
y = 1
print('before try')
try:
print('inside try')
print(x/y)
print('exiting try')
except ZeroDivisionError:
print('exception was handled')
print('continue program')
output
before try
34
try-except – example 2
x = 5
y = 1
print('before try')
try:
print('inside try')
print(x/y)
print('exiting try')
except ZeroDivisionError:
print('exception was handled')
print('continue program')
output
before try
inside try
35
try-except – example 2
x = 5
y = 1
print('before try')
try:
print('inside try')
print(x/y)
print('exiting try')
except ZeroDivisionError:
print('exception was handled')
print('continue program')
output
before try
inside try
5
36
try-except – example 2
x = 5
y = 1
print('before try')
try:
print('inside try')
print(x/y)
print('exiting try')
except ZeroDivisionError:
print('exception was handled')
print('continue program')
output
before try
inside try
5
exiting try
37
try-except – example 2
x = 5
y = 1
print('before try') The try block didn’t
try: raise an exception of
print('inside try') type
print(x/y) ZeroDivisionError, so
print('exiting try') we don’t enter the
except ZeroDivisionError: except block
print('exception was handled')
print('continue program')
output
before try
inside try
5
exiting try
continue program
38
try-except Operation
output
before try
40
try-except – example 3
x = 5
y = 'abc'
print('before try')
try:
print('inside try')
print(x/y)
print('exiting try')
except ZeroDivisionError:
print('exception was handled')
print('continue program')
output
before try
inside try
41
try-except – example 3
x = 5
y = 'abc'
print('before try')
try:
print('inside try')
print(x/y) TypeError!!!
print('exiting try')
except ZeroDivisionError:
print('exception was handled')
print('continue program')
output
before try
inside try
42
try-except – example 3
x = 5
y = 'abc'
print('before try') The except block
try: doesn’t handle
print('inside try') TypeError, so the
print(x/y) exception is not
print('exiting try') handled and the
except ZeroDivisionError: program stops.
print('exception was handled')
print('continue program')
output
before try
inside try
…
print(x/y)
TypeError: unsupported operand type(s)
for /: 'int' and 'str'
43
Example for using try-except
while True:
try:
num = input('number please: ')
num = int(num)
break
except ValueError:
print('Bad number... try again')
print(str(num) + '**2 =', num**2)
44
Handling Different
Exceptions Differently
try:
# Something dangerous
except TypeError:
# Handle type error
except IndexError:
# Handle index error
except:
# Handle all other types
45
Handling Several Exception
Types
46
finally always executed
x = 5
y = 0
print('before try')
try:
print('inside try')
print(x/y)
print('exiting try')
except ZeroDivisionError:
print('exception was handled') The finally block
finally: will be executed
print('reached finally close!') no matter if the
print('continue program') try block raises an
error or not
47
try/except/finally
x = 5
y = 1
print('before try')
try:
print('inside try')
print(x/y)
print('exiting try')
except ZeroDivisionError:
print('exception was handled') The finally block
finally: will be executed
print('reached finally close!') no matter if the
print('continue program') try block raises an
error or not
48
try/except/finally
x = 5
y = 'abc'
print('before try')
try:
print('inside try')
print(x/y)
print('exiting try')
except ZeroDivisionError:
print('exception was handled') The finally block
finally: will be executed
print('reached finally close!') no matter if the try
print('continue program') block raises an
error or not
before try
inside try
reached finally close!
...
print(x/y)
TypeError: unsupported operand type(s)
49 for /: 'int' and 'str'
raise your own Exception
• Suppose you write a function, which can
encounter some error cases.
– Examples: invalid input ; no solution to equation ;
invalid list index.
– Previously, you handled this by printing an error
message. However, the function caller can ignore
this print.
– Raising an exception is the more “built-in” way to
signal something went wrong in your function.
50
raise your own Exception
– raise stops the code’s execution and signals
that specific runtime error was encountered.
The function caller cannot ignore this!
def my_func(x):
…
if some_error_condition:
raise TypeOfException()
51
raise Example –
Quadratic Equation
Find real solutions of 𝑎𝑥 + 𝑏𝑥 + 𝑐 = 0 for given 𝑎, 𝑏, 𝑐.
Possible error conditions:
𝑎=0 Not a quadratic equation.
𝑏 − 4𝑎𝑐 < 0 No real solutions.
In these cases, we’ll raise an exception of type
ValueError.
print('START')
try:
a, b, c = 2, 3, 1
s1, s2 = solve_quadratic(a, b, c)
print(s1, s2)
except ValueError:
print('Problem!')
54 print('Next commands')
Handling exceptions –
Quadratic Equation
print('START') print('START')
try: try:
a, b, c = 2, 3, 1 a, b, c = 0, 3, 1
s1, s2 = solve_quadratic(a,b,c) s1, s2 = solve_quadratic(a,b,c)
print(s1, s2) print(s1, s2)
except ValueError: except ValueError:
print('Problem!') print('Problem!')
print('Next commands') print('Next commands')
Output: Output:
START START
-0.5 -1.0 Problem!
Next commands Next commands
55
Resource Cleanup
Run-time errors are very common in programs
conducting I/O operations
The file we try to open does not exist
The disk runs out of space while we write to a file
56
try/except/finally - Example
finally:
print('closing file')
fhandle.close()
57
finally always runs at the end…
used to free resources
f = None
try:
f = open('testfile.txt', 'w') # f remains None if open fails
f.write('This is it!!')
except IOError:
print("Error: can't find file or read data")
finally:
if f != None: # closing f only if it was opened
f.close()
This finally block always runs after the try block (whether exception
was raised or not). Use it to run commands that are always required
to run at the end – like closing open files.
58 We will use this recipe for handling IOErrors in most cases
with automatically closes the file
The following two code blocks are equivalent: •
try:
f = open('file.txt', 'w') Note: The code in this page
try: includes error handling for both the
f.write('Hello World!') open and the following IO
finally: commands, and also ensures
f.close()
closing of the opened file.
except IOError:
USE ONE OF THESE TWO VERSIONS IN REAL
print('oops!') LIFE FOR FULL PROTECTION AGAINST IO
ERRORS…
------------------------------
try:
with open('file.txt', 'w') as outfile:
outfile.write('Hello World!')
except IOError:
print('oops!')
59
Bonus: Extracting the exception’s error
message
We raised an exception with an error message using raise
E(‘String with more info').
The caller can then extract the string for more info.
try:
a, b, c = 2, 3, 10
solve_quadratic(a, b, c)
except ValueError as err:
print('Problem for a,b,c =', a, b, c, ':', err.args[0])
60