Outline for October 26, 2023
Reading:
§7
Due:
Homework 2, due October 26, 2023
Files
What is a file?
What can you do with it? (For example, read, write, append)
Types of files (text, binary)
File Input and Output for text files
Opening and closing:
open(
filename
,
mode
)
,
close()
Reading:
readline()
,
readlines()
,
read()
,
read(
n
)
Writing:
write(
str
)
,
writelines(
list
)
Exception
EOFError
— input function encounters an end of file
Examples
Print out a named file [
fileio1.py
]
Print out a named file and prepend line numbers [
fileio2.py
]
Store the output in
filename
.lst [
fileio3.py
]
Examples
Put lines in a file in random order [
randlines.py
]
Read in a list of words from a file, then search it as requested; similar to linear search program [
search-1.py
]
Now see how many words you checked total [
search-1c.py
]
Dictionary
Collection of key-value pairs
Creating dictionaries
Using
d = {
}
Using
d = dict()
Methods for dictionaries
k in D
: True if dictionary
D
has key
k
; else False
D.keys()
: list of keys in
D
D.values()
: list of values in
D
D.items()
: list of tuples (key, value) in
D
D.get(k, d)
: if key
k
in
D
, return associated value; else return
d
del D[k]
: delete tuple with key
k
from
D
D.clear()
: delete all entries in
D
Example: memos
Remember how slowly the recursive Fibonacci number program
rfib.py
ran? Here is a faster recursive version that uses memos [
rfibmemo.py
]
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email:
mabishop@ucdavis.edu
ECS 235A, Computer and Information Security
Version of October 25, 2023 at 10:08PM
You can also obtain a PDF version of this.