Calvin (Deutschbein)
Slides by Jed Rembold
9 March 2022
To the right are the contents of a text file named PBride.txt
. Which code snippet below would print off the word “father”?
My name is Inigo Montoya.
You killed my father.
Prepare to die.
with open('PBride.txt') as f:
for line in f:
w = line.split()
if w[0] == "You":
print(w[-1])
with open('PBride.txt') as f:
c = f.read().splitlines()
print(c[1][4])
with open('PBride.txt') as f:
c = read('PBride.txt')
print(c.find("father"))
with open('PBride.txt') as f:
c = f.read()
i = c.find("f")
print(c[i:i+6])
IOError
open
encounters an error, it reports the error by raising an exception with IOError
as its type.
try
try
statement to indicate an interest in trying to handle a possible exceptiontry:
# Code that may cause an exception
except type_of_exception:
# Code to handle that type of exception
type_of_exception
here is the class name of the exception being handled
IOError
for the file reading errors we are discussingtry
block or within functions called within the try block would be “caught”def get_existing_file(prompt="Input a filename: "):
while True:
filename = input(prompt)
try:
with open(filename):
return filename
except IOError:
print("That filename is invalid!")
open
call succeeds, we immediately just return the filename, but if it fails due to a IOError
, we display a message and then keep askingpgl.py
also supports a mechanism to choose files interactively, made available through the filechooser.py
library module.filechooser.py
exports two functions:
choose_input_file
for selecting a filechoose_output_file
for selecting a folder and filename to save a file towith open(filename, mode) as file_handle:
# Code to write the file using file_handle
mode
parameter to open
here! Mode is a string which is either
"w"
to write a new file (or overwrite an existing file)"a"
to append new contents to the end of an existing file.write(some_string)
to write a string to the file.writelines(iterable_of_strings)
to write each iterable element to the filemagic = [ [2, 9, 4], [7, 5, 3], [6, 1, 8] ]
magic[1][1] = 5
magic[-1][0] = 6
[ [2, 9, 4], [7, 5, 3], [6, 1, 8] ]