File Handling Module 1
File Handling Module 1
Introduction:
Data File Handling is a mechanism by which we can read data from disk files into Python program or write back
data from python program to disk files.
So far in our python program, the standard input is coming from Keyboard and output is going to Monitor i.e. no
where the data is stored permanently and the entered data is present as long as the program is running. File
Handling allows us to store data entered through python program permanently in disk file and later on we can
read back the data.
File is a location that stores data permanently pertaining to a specific location. File input/output means
transfer of data from secondary storage device to main memory and vice versa.
The flow of data in a computer system is known as streams. There are two types of streams. Input Stream
and Output Stream. When information is read from a data file (in secondary storage), then the transfer of
data from file to the main memory is called InputStream. When information is written or recorded in a file
then the transfer of data from main memory to file (Secondary Storage) is called Output Stream.
Output Stream/Writing
Input Stream/Reading
A File is a Stream or sequence of characters/data occupying named place on the disk. Python allows us to
manage two types of files. They are: (i) Text Files (ii) Binary Files
Text File-
1. is saved with the extension .txt. It is stored in human readable form and can be created by any text
editor like Notepad.
2. Each line is terminated/delimited by a special character known as EOL (End Of Line) character. The
default EOL character in Python is ‘\n’ i.e. newline character.
3. Some internal translations take place when the EOL Character is read/written.
4. Stores information in ASCII/UNICODE format.
Binary File-
1. Stores information in the same format as it is stored in the memory i.e. in the form of raw bits or
chunk of bytes.
2. There is no delimiter character and hence no internal translation takes place. So reading and writing
from and to to binary file is faster than text file.
3. It is extremely important to interpret stream of bytes to correct datatype while reading and writing.
Creating/Opening a File-
We should first open the file for read or write by specifying the name of file and mode in which the file is
to be opened.
Once the file is opened- now we can either read or write for which file is opened using various functions
available. The basic operations are:
After performing the required operations, we must close the file and release the file for other application
to use it.
Opening a File:
File Modes:
The file mode denotes how the file is opened and how it can be accessed. Different File Modes are: