Dictionaries And Files
Dictionaries
Dictionaries are a way to store data as unordered key-value pairs. This is extremely useful to represent attributes of a single thing.
Features:
Keys are usually strings or ints
Values can be any type
Mutable
Initialization:
Operations:
Files
Opening
To open a file, use the following command:
where mode
can be one of
"r"
to read file (default mode)Returns error if file doesn't exist
"w"
to write to fileRemoves all old data if file exists
Creates file if it doesn't exist
"a"
to append to end of fileCreates file if it doesn't exist
"r+"
to read and write at the same timeReturns error if file doesn't exist
Does NOT remove old data if file exists
Reading
The following functions are available for reading files when you have a stream
available:
stream.read()
reads all textstream.readline()
reads one linestream.readlines()
reads all lines as a list
Pro tip: When reading lines, you'll often have whitespace characters like at the end. Use the string method rstrip
to remove them.
Writing
The following functions are available for writing lines to a file when you have a stream
available:
stream.write(string)
writes textstream.writelines(list_of_strings)
writes multiple lines
Closing
Any time you finish reading/writing/appending to a file, you must remember to close the file. Otherwise, you risk having incomplete changes.
There are 2 ways to close a file:
Last updated