File Handling in Python
Text file programs and pickle
Store and read Python objects with pickle.
Creating and reading text files in programs:
- Opening an existing file in w mode erases its contents; opening it in a mode adds after the existing data. Both modes create the file if it does not exist.
- To read a file line by line, call readline() in a loop, and stop when it returns an empty string (the end of the file).
- In w+ mode, one file object can write, then seek(0) back to the start, and read what was written.
Storing Python objects: the pickle module. Text files can only store strings. To save objects such as lists or dictionaries exactly as they are, Python uses the pickle module.
- Pickling (also called serialization) turns a Python object into a stream of bytes, which can be stored in a binary file.
- Unpickling (deserialization) turns the bytes back into the original object.
Two methods do the work:
- pickle.dump(object, file_object) writes the object to a file opened in binary write (wb) or append (ab) mode.
- pickle.load(file_object) reads one object back from a file opened in binary read (rb) mode.
To read every object stored in a file, call pickle.load() in a loop. When there is nothing left, load() raises an EOFError, so the loop is placed in a try block and stops when that exception is caught.
dump saves objects to a file; load gets them back.
Practise this lesson
Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.
No account, no email address. Opens the real product.