0% found this document useful (0 votes)
11 views

slide set 6

Uploaded by

hannah.cohen2009
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

slide set 6

Uploaded by

hannah.cohen2009
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Slide set # 6

I\O & Exceptions


Introduction to Programming for Engineers
Dr. Inon Zuckerman, Dr. Chen Hajaj
Industrial Engineering and Management
Output to the screen – print()

• The print() function print a message to the


screen (or to other output devices)
• The message can be String or any other
object. An object is converted to String and
then written to the screen
• Syntax:
print(object(s),sep=separator,end=end,file=file,flush=flush)

2
Output to the screen – print()
print(object(s), sep=separator, end=end,
file=file, flush=flush)

• object(s) are printed as String


• separator is entered between the printed
objects. The default separator is space
• end is entered after the last object. The
default end is ‘\n’ (new line)
• file tells print() where to print. The default is
sys.stdout (the screen)
• flush is a Boolean that specifies if the output
is flushed or buffered
>>> print('a','b',sep='-',end=' ' + 'end' + '\n\n')
3 a-b end
File and Folders
• A Computer-File is a resource for storing information;
A “digital” document
• Files are organized in folders (=directories).
• Every file has an address (path) in the computer’s file
system
– Example: C:\Desktop\ta5_code\test_file.txt
• The file’s extension represents its content type (txt,
exe, mp3, avi, jpg)
– Text files are composed of a sequence of characters
– Binary files store a sequence of bytes representing any
information (not necessarily encoding for characters)
4
The file system hierarchy
C:\

Python (Current directory)

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

• Text files are composed of lines of text


• Every line is composed of a sequence of
characters
• The last character on every line is the special ‘end
of line’ character ('\n'), usually hidden by most
text editors

7
Opening a connection to a file

• open() returns a file object.


• Most used with two arguments:
open(filename, mode).
– filename: an address of a file.
– mode:
• 'r' – read
• 'w' – write - overwrites prior data
• 'a' – append - adds at end of prior data

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'

>>> f.close() # releases the file lock, frees resources

# 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

<_io.TextIOWrapper name='C:/Users/Desktop/ta5_code/test_file.txt' mode='r' encoding='cp1252'>

>>> f.read()

'This is a file'

>>> f.close()

9
Note about ‘\’
f=open('C:/Users/Desktop/targil/test_file.txt','r') •

But \ is normally used to indicate control characters.

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.

• open a connection to the file you wrote using


my_file=open(“file_name.txt”)

• read the text that you wrote by using


file_content=my_file.read() and print the content
of the file to the screen: print(file_content)
11
Reading the text file line by line

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.

>>> a_line = 'This is a line\nSecond line'


>>> a_line
'This is a line\nSecond line'
>>> print(a_line)
This is a line
Second line

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"

cities = s.split(',') topeka


kansas city
for city in cities: wichita
print(city)
olathe

If a delimiter is not specified, the string is split to


15 words separated by a sequence of whitespaces.
Let’s work – Q2
• Write the following two lines to a new file:
‘a,line,separated,by,comma’
‘a-line-separated-by-dash’
and save the file
• open a connection to the file you wrote and read
the file lines: file_lines=my_file.readlines()
• Split the first line by ‘,’ and the second line by ‘-’
and print the result

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'

• The string method rstrip() can be used to get rid of


trailing newlines (right-strip):
lines = ['this is line 1\n', 'this is line 2\n', 'the end']
for i in range(len(lines)):
lines[i] = lines[i].rstrip()
print(lines) What does lstrip() do?

17['this is line 1', 'this is line 2', 'the end']


Let’s work – Q3
• Download from moodle the file
word_frequencies.txt
• Create a dictionary as a frequency table of the
words in the file.

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()

for w in sorted(d.keys(), key = d.get, reverse = True):


print(w + ":", d[w])

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")

for item in my_list:


f.write(str(item) + “\n")

f.close()

21
Summary
>>> fname = 'myfile.txt'

>>> f = open(fname, ’r’) lines holds a list of strings.


>>> lines = f.readlines() Each line from fname is a
>>> f.close() separate string in this list.

>>> f = open(fname, ’r’) firstline holds the first row


>>> firstline = f.readline() from fname as a string,
>>> secondline = f.readline() while secondline holds the
second line from fname.
>>> f = open(fname, ’r’)
>>> for l in f:
The second word from
each row in fname is
... print(l.split()[1])
printed.
>>> f.close()

Creates a new txt file (or


>>> outfname = 'myoutput.txt'
overwrites, if a file with
>>> outf = open(outfname, 'w')
same name and path
>>> outf.write('My very own file\n')
exists) with one line in it:
22
>>> outf.close() My very own file
Exceptions
Handling runtime errors

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.

 Commands in the try block are executed…


 If no exception is raised by any command: Skip the except block.
 If an exception of type TypeOfException is raised by one of the
commands in the try section, leave the try section and jump to
execute the except block.
27
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

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

• The commands in the body of try execute


• If exception of type E occurs at some command:
– Skip the rest of the try commands
– If E matches TypeOfException:
• Run the commands in the body of except

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

• The commands in the body of try execute


• If exception of type E occurs at some command:
– Skip the rest of the try commands
– If E doesn’t match TypeOfException:
1. Exception “goes up” to the caller of try.
2. If caller doesn’t handle it – program terminates.
39
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

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

 Actually, why not catch and ignore all exception types?

  Our program would never terminate due to error.

  But we’d also miss run-time problems and logical errors.

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.

def solve_quadratic(a, b, c):


if a == 0:
raise ValueError('Not quadratic')
delta = b**2 - 4*a*c
if delta < 0:
raise ValueError('No real solution')
sol1 = (-b + delta**0.5) / (2*a)
sol2 = (-b - delta**0.5) / (2*a)
52
return (sol1, sol2) # possibly sol1 = sol2
raise Example –
Quadratic Equation
 Executing the function with certain inputs will trigger a
runtime error
def solve_quadratic(a, b, c):
if a == 0:
raise ValueError('Not quadratic')
delta = b**2 - 4*a*c
if delta < 0:
raise ValueError('No real solution')
sol1 = (-b + delta**0.5) / (2*a)
sol2 = (-b - delta**0.5) / (2*a)
return (sol1, sol2) # possibly sol1 = sol2
>>> solve_quadratic(0,3,4)
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
solve_quadratic(0,3,4)
File "C:\Users\Owner\Desktop\test_pyeng.py", line 3, in solve_quadratic
raise ValueError('Not quadratic')
ValueError: Not quadratic
53
raise Example –
Quadratic Equation
What if we want to handle runtime exceptions and then
continue running the program (avoid program crashing)?

def solve_quadratic(a, b, c):


if a == 0:
raise ValueError('Not quadratic')
delta = b**2 - 4*a*c
if delta < 0:
raise ValueError('No real solution')
sol1 = (-b + delta**0.5) / (2*a)
sol2 = (-b - delta**0.5) / (2*a)
return (sol1, sol2) # possibly sol1 = sol2

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

 Catching IO-Exceptions allows proper handling of


such cases.

56
try/except/finally - Example

fhandle = open('file1.txt', 'w')


try:
fhandle.write('File for exception
handling')
except IOError:
print('Error')

finally:
print('closing file')
fhandle.close()

Note: Exceptions raised by the open command are not


handled in the code above.

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

You might also like