File input and output:
- File handling is a mechanism
by which we can read data off disk files in python program or write back data
from python program to disk files.
- So far in our python program the standard input is coming from the keyboard and output is going to monitor i.e. no where data is stored permanently and entered data is present as long as program is running but file handling allows us to store data entered through python program permanently in a disk file and later on we can read back the data.
- The data files can be stored in two ways
1. Text File
2. Binary File
Steps in Data File Handling:
1. OPENING FILE
- The file can be opened for either – read, write, append.
- The default mode is “read”.
View current path for created files or
viewing create files where are stored in python:
Output:
2. PERFORMING READ/WRITE/APPEND
- Once the file is opened now we can either read or write for which file is opened using various functions available.
- After performing the operation we must close the file and release the file for other applications to use it.
Text File handling:
Write any data into the file using file
handling:
Output:
Output:
Read data from the file using file handling:
Output:
To copy the content of one file to
another file:
Output:
with statement:
- Python’s “with” statement for the file handling is very handy when you have two related operations which you would like to execute as a pair, with a block of code in between:
- The advantage of “with” is it will automatically close the file after the nested block of code.
- It guarantees to close the file how nested block exits even if any run time error occurs.
Example program:
Output:
Binary file operations:
- The binary file is nothing but, It is used to convert normal text file into an unreadable format using pickle module in python.
Pickle:
- Pickling is the process of converting structure to a byte stream before writing to a file and while reading the content of file a reverse process called Unpickling is used to convert the byte stream back to the original format.
Steps to perform binary file operations:
Step 1: First we need to import the module called pickle.
Step 2: This module provides 2 main
functions:
1. dump() : to
write the object in the file which is loaded in binary mode
Syntax : dump(object_to_write,
filehandle)
2. load() :
dumped data can be read from a file using load() i.e. it is used to read object
from pickle file.
Step 3: Close the file.
Example program:
Output:
No comments:
Post a Comment