Unit 5.1 File Handling
Unit 5.1 File Handling
Subject Expert
Prof. M. V. Tiwari
File Types :
➢Python can handle two types of files.
I. Text files (.txt)
II. Binary files (Audio, Video, Images, etc.)
File Operations :
➢It takes place in the following order :
I. Open a file
II. Perform file operations (read / write / append)
III.Close the file.
Syntax
f = open(“filename”, “mode”, “buffering”)
open() :- this function opens a file and returns a file object (file handle).
mode :-
➢On closed file any operation would lead to exception: ValueError: I/O operation
on closed file.
➢If an exception occurs when we are performing some operation with file, the code
exits without closing the file.
➢The os module provides a big range of useful methods to manipulate files and
directories.
▪remove() : it is used to delete file.
▪rename() : it is used for renaming the current file name with new file name.
dump( ) :
➢It takes aserializable Python data structure (list, dictionary etc), serializes it into
binary in an open file.
load( ) :
➢It takes a stram object, reads the serialized data from the stream, creates a new
Python object, recreates the serialized data in the new Python object and returns
the new Python objects.