Year 1 Computer Programming - Lecture 8
Year 1 Computer Programming - Lecture 8
(Based on Gaddis, T., Starting out with Python 3e, Pearson Education)
Introduction to File
Writing Data to File
Reading Data From File
Exceptions Handling
– Direct access: can jump directly to any piece of data in the file
read method: file object method that reads entire file contents into
memory
– Only works if file has been opened for reading
– Contents returned as a string,
– Format: content = file_variable.read()
readline method: file object method that reads a line from the file
– Line returned as a string, including '\n‘
– Format: line = file_variable.readline()
Files typically
used to hold
large amounts
of data and
Often the
number of
items stored in
file is
unknown.
Loop typically
involved in
reading from
and writing to
a file
Example
file.close()
When open file with 'w' mode, if the file already exists it is
overwritten
To append data to a file use the 'a' mode
– If file exists, it is not erased, and if it does not exist it is created
– Data is written to the file at the end of the current contents
x = "blue,red,green"
colours = x.split(",")
print(colours)
def get_employee_info(self):
print( "Employee name is: %s" %self.name)
print("Employee age is: %d" %self.age)
print("Employee salary: is %f" %self.salary)
emp1_lst = employee_1.split(",")
emp2_lst = employee_2.split(",")
emp1_obj.get_employee_info()
print() # new line
emp2_obj.get_employee_info()
try:
statements
except exceptionName:
statements
Often code in try suite can throw more than one type of exception. Need to
write except clause for each type of exception that needs to be handled
>>> >>>
Enter Number 1 : 12 Enter Number 1 : 12
Enter Number 2 : two Enter Number 2 : 0
Traceback (most recent call last): Traceback (most recent call last):
.. .. .. .. ... .. .. .. .. .. ..
... .. .. .. .. .. .. .. ..
ValueError: invalid literal . .. ...... ZeroDivisionError: division by zero
Often code in try suite can throw more than one type of exception. Need to
write except clause for each type of exception that needs to be handled
>>>
Enter Number 1 : 12
Enter Number 2 : 0
Divisor can not be zero
CMP 4266, School of CS & CD, Birmingham City University.
Handling Multiple Exceptions
An except clause that does not list a specific exception will handle any
exception that is raised in the try suite
>>> >>>
Enter Number 1 : 12 Enter Number 1 : 10
Enter Number 2 : two Enter Number 2 : 0
Invalid input, please check your input Invalid input, please check your input
def main():
total = 0
try:
infile = open('sales_data.txt', 'r')
string = infile.readline()
except FileNotFoundError as exp:
print(exp)
try:
statements
except exceptionName:
statements
else:
statements