Objects
- A value is some data in memory together with its type (
int
,float
, etc.) - An object is similar; however,
- Tends to be more complex (e.g, have many parts)
- Tends to have operations assigned to it.
- Examples: List, String, Date
- The difference between values and objects is not precisely defined (and not highly important)
- Sometimes functions are tightly bound to an object (i.e., don’t make much sense in a more global context)
String#startswith
- This function doesn’t really make sense as a “global” function, since it really only applies to strings.
- So, we bundle it with the class, call it a
method
, and call it like this: my_string.startswith('foo')
- Other common string methods:
startswith
endswith
index
strip
upper
lower
split
join
- More: https://www.w3schools.com/python/python_ref_string.asp
Files
- Calling the global
open
function returns aFile
object that can be used to read or write files.f = open('my_file.txt', 'r')
- Filename can be (a) absolute or (b) relative to the current working directory.
- Four common methods to call on a file object
read
— entire file as one stringreadlines
— entire file as a listreadline
— one line at a time.close
— close the file when finished.
- Take care to only use
read
andreadlines
with small files. - Short-cut that will automatically close the file for you.
with open('the_file.txt', 'r') as f:
for line in f:
# do stuff
- finish IC-8
CSV
- Comma-separated value
- In principle, we can simply take a line, call
split
and look at the parts. - When might this fail?
- What if data contains a comma?
- A more robust solution is to use a library that handles all of the “what ifs”
import csv
def sample_open_csv(filename):
with open(filename) as csv_file:
f = csv.reader(csv_file)
next(f, None) # skip the header row
for row in f:
print(row)
- remember the
include csv
- Short-cut: List comprehension:
row = [int(val) for val in raw_row]
- Show the “long” version of above.
DictReader
import csv
def sample_open_csv(filename):
with open(filename) as csv_file:
f = csv.DictReader(csv_file)
# _don't_ call next
for row in f:
print(row)
Topics for later:
- Use pandas or numpy to read csv
- Dictionary comprehensions