Study Guide for Quiz over dictionaries, strings, reading/writing files - These are chapters 5, 6, 9 in https://automatetheboringstuff.com/ - Note - this study guide has what you need to know, you don't need to study all of the content in those chapters NOTE - items marked ## are NOT included on the quiz or final exam. They are for your information only, and you can ignore them on your first pass through this material (and in studying). These are good to know, but you can get by without them. ** Dictionaries ** - Like lists but where "index" can be any immutable value - index can be a string, number, etc., and is called a "key" rather than "index" - Create with d = {'key1':'value1', 'key2':'value2'} - Access value at 'key1' with d['key1'] - and just like any variable can be used for getting the current value or setting a new value - Loop through keys for key in d: print(key, d[key]) - Methods * d.keys() - list of all keys * d.values() - list of all values * d.items() - list of (key, value) pairs ## d.get('key', 'othervalue') - returns d['key'] if 'key' is in d, or 'othervalue' if not ## d.setdefault('key', 'othervalue') - sets d['key']='othervalue' if 'key' is not in d, returns d['key'] if 'key' was already in d - Check for key using - 'key' in d, or using - 'key' in d.keys() - Check for value using - 'value' in d.values() - Note that the values in the dictionary can be lists, tuples, or dictionaries, or can be just strings or numbers. - Note that the keys in the dictionary must be an "immutable" data type - numbers, strings, tuples, Boolean. Strings - can use 'single quotes', "double quotes", or '''triple single/double quotes''' * triple quotes can be across multiple lines - access individual characters like tuples/lists, s[i] - immutable (as are tuples) - canNOT do s[i] = 'a' - escape characters, since often cannot be directly typed: \', \", \n for newline, \t for tab, \\ for slash * try: print('\'he\'llo\'') * try: print('1\n2\n3') * try: print('I like to say 'hello' to everyone!') # this is an error... ## r"raw string - escape characters are not evaluated, so \' is two characters and not one" - slices, s[start:end] returns substring going from index start up to end (including index end-1 but not end) * s[:end] goes from beginning of string, s[start:] goes until end - 'a' in s - True/False if 'a' is contained in s - 'a' not in s - string concatenation with +, e.g., 'I am ' + str(600) + ' years old!' - string multiplication with *, e.g., 'hi! '*4 - functions * str - converts other types to string * len - number of characters - string methods * isalpha, isdigit - only letters, only digits * 'some string'.split() - returns list of words in the string * ' '.join(['some', 'words']) - concatenates strings ## find - returns index of first occurrence of a substring ## upper, lower - returns upper-case/lower-case version ## isupper, islower - returns True if string is all upper/lower case characters ## 'some string'.startswith('some') - returns True/False ## endswith - similar ## interpolation strings - 'string with a %s marking a %s to be put in' % ('something', 'value') ## format strings - f'string with expressions in {3+3} that are evaluated' Reading/writing Files - Filenames either start at the "current working directory", or can have the directoy path as part of the name. * Directory folders - separated in the filename with / on linux/macOS and with \ on Windows. * \ on Windows - \ is used in strings for escape characters, to have an actual \ in a filename, either use '...\\...' or r'...\...' * absolute path - starts at the very top of the directory structure * relative path - starts from current working directory, e.g., 'project/something.txt' * Examples with directory "absolute" path/folders + Windows: 'c:\\Users\\Jkinne\\Documents\\something.txt' + MacOS: '/Users/jkinne/Documents/something.txt' + Linux: '/u1/class/cs15100/project/something.txt' ## Functions/Modules in python for dealing with file names and such ## os module - os.chdir('directory to change to'), os.getcwd(), os.mkdir('directory to create'), os.path.abspath('some file'), os.basename('directory/file') gives the filename, os.path.dirname('directory/file') gives the directory, os.path.getsize('some file'), os.path.listdir('some directory'), os.exists('some file'), os.isdir('some file'), os.isfile('some file') - functions for reading/writing files * f = open('someFile.txt', 'r') allFile = f.read() f.close() print(allFile) f = open('someFile.txt', 'w') f.write('some text to write to the file\n') f.write('some more text to write to the file.') f.close() * key 4 functions - open, read, write, close * open, the second parameter - 'r' for reading, 'w' for writing a new file or overwriting an existing one, 'a' for appending to an existing file * other ways to read from an open file variable f lines = f.readlines() # lines will be a list of all of the lines of the file # or for line in f: # loops through all of the lines in the file print(line) ## other ways to save/load data from python files - shelve module, pickle module, ask the internet