Files and file objects (in Python)
Transcript of Files and file objects (in Python)
Files
Python SIG – PYA Class 5 – 7/11/15
(Revision of) Tuples
• Tuples are “immutable lists”• A tuple is not ‘()’ it is ‘,’• ‘count’ and ‘index’ methods• You can slice, and (negative) index tuples, like lists• You can use ‘in’ to see if a tuple contains a
particular element• You can convert a list to a tuple and vice versa
with tuple() and list()
(Revision of) Dictionaries
• key – value pairs• keys have to be immutable• values don’t• dict methods – mainly .keys(), .values()
and .items()• They return a list, list and list of tuples
repectively
(Revision of) Dictionaries
• dict[valid_key] = corresponding_value• dict[invalid_key] gives a KeyError• .get(key, default_value) when we don’t want
the program crashing because of KeyErrors• .keys() won’t return alphabetically sorted list• Can use sorted() or .sort()• sorted() preferred (other won’t work in Py3)
(Revision of) try except else finally
try:#potentially dangerous code
except TypeError, err_info:print 'type’, err_info
except ImportError, err_info:print ‘import’, err_info
else:print ‘no errors’
finally: # cleanup code (like closing a file)
(Revision of) assert
• assert condition, ‘Error info’• If condition evaluates to False, an
AssertionError occurs• To make program “fail fast”• You’ll know where it happened
(Revision of) raise
• raise Exception(“Error!”)• Again, “fail fast”• Can replace error description with our own• A list of exceptions can be found on the online
documentation – https://docs.python.org/2/library/exceptions.html
(Revision of) with
• Mainly used for file r/w operations• Alternative to try except in these cases• with open(‘filename.txt’) as f1:
f1.close()
FileIO
• File objects are used for rw operations• f1 = open(‘filename.txt’, ‘r’)• (no, not that f1)• ‘r’ is by default• ‘w’ creates file if it doesn’t exist, erases if it
does• ‘a’ is used to preserve data
Assignment
• Write a program in the Python interpreter to print the name and information in help() of all file methods that do not start with ‘__’ (two underscores).
• To those who have finished, read them!
Files and File objects
• .read() is useful if the file is small. (basically, can fit in RAM) It reads the entire file as a string.
• .readline() reads a single line. (defined by line endings \n \r \r\n depending on OS)
• .readlines() returns a list of all lines• .seek(0) goes to the beginning of the file• Think of the file object as a DVD player
Files and File objects
• .write() and .writelines() are used to write to a file. The first one takes a string argument and second one a sequence of strings.
• Don’t forget to add newlines.• Don’t forget to close files.• Most of these methods have optional size
arguments.
with
• Files can be opened multiple times• with open(‘filename.txt’) as f1:
# do something# no need to end with f1.close()
• Always closes the file; no matter what.
Assignment
• Using a single file object, first read a .txt file and print its contents. Then ask the user whether to erase the contents or add something and extend the file.. Write the data entered by the user to the file if the user chooses the second option.