07_Python_Lecture
07_Python_Lecture
6-1
Introduction to File Input and Output
• For program to retain data between the times it is run,
you must save the data
– Data is saved to a file, typically on computer disk
– Saved data can be retrieved and used at a later time
• “Writing data to”: saving data on a file
• Output file: a file that data is written to
6-2
Introduction to File Input and Output
• “Reading data from”: process of retrieving data from a
file
• Input file: a file from which data is read
6-3
Types of Files and File Access Methods
• In general, two types of files
– Text file: contains data that has been encoded as text
– Binary file: contains data that has not been converted
to text
• Two ways to access data stored in file
– Sequential access: file read sequentially from
beginning to end, can’t skip ahead
– Direct access: can jump directly to any piece of data in
the file
6-4
Filenames and File Objects
• Filename extensions: short sequences of characters
that appear at the end of a filename preceded by a
period
– Extension indicates type of data stored in the file
File1.pdf
File2.txt
File3.py
6-5
Opening a File
• open function: used to open a file
– Creates a file object and associates it with a file on the
disk
– General format:
– file_variable = open(filename,
mode)
• Mode: string specifying how the file will be opened
– Example: reading only ('r'), writing ('w'), and
appending ('a')
6-6
Specifying the Location of a File
• If open function receives a filename that does not
contain a path, assumes that file is in same directory
as program
• If program is running and file is created, it is created in
the same directory as the program
• Can specify alternative path and file name in the open
function argument
Prefix the path string literal with the letter r
open(r'C:\Users\jyu3\Downloads\temp.txt',
'r')
6-7
Writing Data to a File
• Method: a function that belongs to an object
– Performs operations using that object
• File object’s write method used to write data to the
file
– Format: file_variable.write(string)
6-8
Reading Data From a File
• read() method: reads entire file contents into
memory
– Only works if file has been opened for reading
– Contents returned as a string
• readline() method: file object method that reads a
line from the file
– Line returned as a string, including '\n’(new line)
• Readlines() method: reads all lines of the file and
returns them as a list of Strings.
6-9
Appending Data to an Existing File
• When open file with 'w' mode, if the file already
exists it is overwritten
6 - 10
Writing and Reading Numeric Data
• Numbers must be converted to strings before they are
written to a file
• str function: converts value to string
• Number are read from a text file as strings
– Must be converted to numeric type in order to perform
mathematical operations
– Use int and float functions to convert string to
numeric value
6 - 11
Using Python’s for Loop to process
files
• Python allows the programmer to write a for loop that
automatically reads lines in a file and stops when end
of file is reached
– Format:
for line in file_object:
statements
6 - 12
Using Python’s for Loop to process
files
– Example ( three steps to use a file )
–
f = open( ‘some file’, ‘r’ )
for line in f:
# your logic to process each line
f.close()
6 - 13
Open files using with statement
• with statement creates a context manager, ensuring
that resources (like files) are properly managed
Format:
with open( ‘some file’, ‘r’ ) as f:
for line in f:
# your logic to process each line
6 - 14
Practice questions
• 1. Create a file temp.txt, add at least two lines in it.
• 2. Write a program to read the file, print the content
( display line by line )
• 3. modify the program you wrote in question 2, print
the content but the first line ( skip the first line)
• 4. write another program that creates a new file
temp2.txt, write the content of temp1.txt to it ( copy the
content from temp1.txt to temp2.txt )
6 - 15
Exceptions
• Exception: error that occurs while a program is
running
– Usually causes program to abruptly halt
• Traceback: error message that gives information
regarding line numbers that caused the exception
– Indicates the type of exception and brief description of
the error that caused exception to be raised
6 - 16
Exceptions
• Many exceptions can be prevented by careful coding
– Example: input validation
• Some exceptions cannot be avoided by careful coding
– Examples
Trying to convert non-numeric string to an integer
Trying to open for reading a file that doesn’t exist
6 - 17
Exceptions
• Exception handler: code that responds when
exceptions are raised and prevents program from
crashing
– In Python, written as try/except statement
General format:
try:
statements
except exceptionName:
statements
6 - 18
Exceptions
Format for catching all exceptions :
try:
statements
except: # catch all exceptions
statements
6 - 19
Exceptions
• If statement in try block raises exception:
– Exception specified in except clause:
Handler immediately following except clause executes
Continue program after try/except statement
– Other exceptions:
Program halts with traceback error message
6 - 20
Built-in Exceptions
• There are many built in exceptions in Python:
• ValueError
• TypeError
• ArithmeticError
• Exception
• IndexError
• MemoryError
• …
6 - 21
Handling Multiple Exceptions
• Often code in try block can throw more than one type
of exception
– Need to write except clause for each type of
exception that needs to be handled
• An except clause that does not list a specific
exception will handle any exception that is raised in
the try block
– Should always be last in a series of except clauses
6 - 22
Handling Multiple Exceptions
Format:
try:
statements
except TypeError:
statements
except ValueError:
statements
except IndexError:
statements
6 - 23
Displaying an Exception’s Default Error
Message
• Exception object: object created in memory when an
exception is thrown
– Usually contains default error message pertaining to
the exception
– Can assign the exception object to a variable in an
except clause
Example: except ValueError as error:
– Can pass exception object variable to print function
to display the default error message
6 - 24
The else Clause
• try/except statement may include an optional
else clause, which appears after all the except
clauses
– Aligned with try and except clauses
– Syntax similar to else clause in decision structure
– Else suite: block of statements executed after
statements in try suite, only if no exceptions were
raised
If exception was raised, the else suite is skipped
6 - 25
Handling Multiple Exceptions
Format:
try:
statements
except TypeError:
statements
except ValueError:
statements
except IndexError:
statements
else: # optional
statements
6 - 26
The finally Clause
• try/except statement may include an optional
finally clause, which appears after all the except
clauses
– Aligned with try and except clauses
– General format: finally:
statements
– Finally block: block of statements after the finally
clause
Execute whether an exception occurs or not
Purpose is to perform cleanup before exiting
6 - 27
Handling Multiple Exceptions
Format:
try:
statements
except:
statements
else: # optional
statements
finally: # optional
statements # always executed
6 - 28
Handling Multiple Exceptions
Format:
try:
statements
except TypeError:
statements
except ValueError:
statements
except IndexError:
statements
else: # optional
statements
6 - 29
Practice questions
1. Add try except blocks to the practice questions of file
processing.
6 - 30