Text File
Text File
Binary Files
Binary files are also stored in terms of bytes (0s and 1s), but unlike text files, these
bytes do not represent the ASCII values of characters. Rather, they represent the actual
content such as image, audio, video, compressed versions of other files, executable
files, etc. These files are not human readable. Thus, trying to open a binary file using
a text editor will show some garbage values.
We need specific software to read or write the contents of a binary file.
Pickle module
Python pickle module is used for serializing and de-serializing a Python object
structure. Any object in Python can be pickled so that it can be saved on disk. What
Pickle does is it “serializes” the object first before writing it to a file. Pickling is
a way to convert a Python object (list, dictionary, etc.) into a character stream. The
idea is that this character stream contains all the information necessary to reconstruct
the object in another Python script. It provides a facility to convert any Python object
to a byte stream. This Byte stream contains all essential information about the object so
that it can be reconstructed, or “unpickled” and get back into its original form in any
Python.
• write() method takes a string as an argument and writes it to the text file.
• writelines() method is used to write multiple strings to a file. We need to pass an
iterable object like lists, tuple etc. containing strings to writelines() method.
• read([n]) method is used to read a specified number of bytes (n) of data from a data
file.
• readline([n]) method reads one complete line from a file where lines are ending with a
newline
(\n). It can also be used to read a specified number (n) of bytes of data from a file but
maximum up to the newline character (\n).
• readlines() method reads all the lines and returns the lines along with newline
character, as a list of strings.