3, File Handling
Each line oc text is Thcrc is no
Key Points
Need of File Handlin o? terminated with a dclimitcr in Binary
A file in itself is a bunch of bytes stored on special character Filc.
some storage device. known as E()L (End
File helps us to store the data pennanently of I ,inc)
which can be retrieved for tilture use. Text files arc easy to Binary filcs arc
understand because difficult to
Tstves of Files :
these files are in understand.
human readable
csv form.
TextFiles Binary Files
Files Text files are slower Binary files are
than binary files. faster and easier for
Text Files: a program to read
Stores information in ASCII or Unicode and write than the
characters. text files.
Each line of text is terminated with a special Text files are having Binary files are
character known as EOL (End of Line). extension .txt having extension
Extension for text files is .txt .dat
Default mode of file.
Binary Files: Two methods to open a File.
Contains information in the same format in Using open ( ) function
which the information is held in memory. Using with statement
There is no delimiter for a line. How to open a text file ?
FileObject = open(<filename>)
No translations are required. OR
More secure. FileObject = open(<filename>,<mode>)
Difference between Text files and Binary
Files: Path toa Mode of at
Text Files Binary Files Examples:
Text files stores Binary files are used open ("myfile .txt" 'r')
information in to store binary data F= open
ASCII characters. such as images, Desktop \\ Text File .txt", "r" )
audio, video and open (r "C: \ Users\sony \
text. Desktop \ TextFi1e. txt" ,
58
Question bank - Class Xll (Computer Science)
, Using with statement: In r+ mode, the file In w+ mode, the file
This method is very handy when you have pointer is at the pointer is at the end of
two related operations which you would like beginning of the file. the file.
to execute as a pair , with a block of code in
between. If the file does not If the file does not
Syntax : exists, it will display exist, it will create the
the FileNotFound new file.
with open <FileMode>) as IEwor.
I <File Handle :
f.mite( If the filc exist, it If the file exists, it will
Benefits of usino statevncn(: doesn't show any write the data in the
It automatically closes the file after the nested error. file (overwriting the
previous content).
block of code.
It also handles all the exceptions also
occured before the end of block. Reading Data from a file
Example : open ("Output.txt","w") as f: 1. read() :
f.wHte ("Text") Reads at most n bytes ; if no n is
File Access Modes: specified , reads the entire file.
r —Opens a file for reading only. This is Default Returns the read bytes in the form of a
mode. string.
rb —Opens a file for reading only in Binary Syntax: <Filehandle>.read([n])
format. This is the default mode. 2. readline()
r+ —Opens a file for both reading and writing. Reads a line of input ; if n is specified
I
rb+ —Opens a file for both reading and writing reads at most n bytes.
in binary format. Returns the read bytes in the form of a
w —Opens a file for only. Overwrites the string ending with '\n' character.
file, if already exists, else creates a new file. Returns a blank string if no more bytes
wb —Opens a file for writing only in binary are left for reading in the file.
format. Syntax : <Filehandle>.readline()
wb+ —Opens a file for both reading and writing 3. readlinesO
in binary format. Reads all the lines of a text file.
a —Opens a file for appending. The file pointer is Returns in the form of list.
at the end of the file if the file exists. If the file Syntax : <FileHandle>.readlines()
doesn't exists, it creates a new file for writing.
ab —Opens a file for appending in binary format. Writing data in a File.
a+ —Opens a file for both appending and reading. While writing data in a file : --- > If file
ab+ —Opens a file for both appendingand doesn't exists, it will create the new file.
reading in binary format. If file exists, it will write the data in the file.
Difference between r+ and w+ mode 1. write(string)
r+ mode w+ mode write( ) method takes a string and writes
Used for both reading W+ mode is also used it in the file.
and writing. for both reading and
writin .
Question bank - ClassXll (Computer Science) 59
, For storing data.
VOLchar-actct, • Audio files: .mp3, .mka, .aac etc.
have to add '\n' character to
the end of • Archiye filee .7ip. .rar, .iso. .77 etc.
the string.
For storing numcnc • Vxecutab!e files: .exe. .dl!. .clags etc.
we have to We can open •ome binary files in the
either convclt it into sting using
) or text editor hut we can't read the
NATite
in quotes..
2. content pre«ent inside the file.
I hat's becauqe all the binary files will he
) method is used to "Tite
encoded in the binary format, which can
sequence data in a file(stnng.list be understoodonly by a computeror a
and tuple etc.)
machine.
-Appcndinc data to a filc
In binary files, there is no delimiter to end
Append means to add the data at the end
a line.
of file using 'a' mode.
Since they are directly in the form of
If file doesn't exists, it NOIIcreate the new
binary, hence there is no need to translate
file.
them.
If file exists, it append the data at the That's why these files are easy and fast in
end of a file. .%hcaUÅxorking.
Closina Files : H)icklino refers to the process of converting
A close() function breaks the link of file - the structure (such as list or dictionary) to a
object and the file on the disk. byte stream before w-rit@æåothe file.
After close(), no tasks can be performedon ÄJnpickling rees to the process of
that file through file object or file —handle. converting the byte stream back to the
Syntax : <FileHandle>.close() original structure.
Example: F.close() pickle.dump() : Used to WI-itethe object in a
file.
Path : The full name of a file or directory or Syntax:
folder consists of path. Path is a sequence of pickle.dump(<Strueture>,FileObject)
directory names which give you the hierarchy to Where, Structure can be any
access a particular directory or file name. sequence of Python. It can be either list or
Absolute Path:—) // dictionary.
The absolute paths are from the topmost FileObjeet is the file handle of the
level of directory structure. file, in which we want to WI-ite.
Relative Path : pickle.load() : Used to read the data from a
The relative paths are relative to the current file.
working directory, denoted as a dot (.) , while Syntax: Structure
its parent directory is denoted with two pickle.load(FileObject)
dots(.,) Where, Structure can be any sequence of
Binary Files : Python. It can be either list or dictionary.
Most of the files that we see in our File()bject is the file handle of the file, in
computer system are called binary files. which we want to mite.
Example: Random Access in Files: 1. seek() : seek()
• Image files: .png, .jpg, .gif, -bmp etc. function is used to change the position of the file
• Video files: .mp4, .3gp, .mkv, .avi etc.
Question bank - Class Xll (Computer Science)
Each line oc text is Thcrc is no
Key Points
Need of File Handlin o? terminated with a dclimitcr in Binary
A file in itself is a bunch of bytes stored on special character Filc.
some storage device. known as E()L (End
File helps us to store the data pennanently of I ,inc)
which can be retrieved for tilture use. Text files arc easy to Binary filcs arc
understand because difficult to
Tstves of Files :
these files are in understand.
human readable
csv form.
TextFiles Binary Files
Files Text files are slower Binary files are
than binary files. faster and easier for
Text Files: a program to read
Stores information in ASCII or Unicode and write than the
characters. text files.
Each line of text is terminated with a special Text files are having Binary files are
character known as EOL (End of Line). extension .txt having extension
Extension for text files is .txt .dat
Default mode of file.
Binary Files: Two methods to open a File.
Contains information in the same format in Using open ( ) function
which the information is held in memory. Using with statement
There is no delimiter for a line. How to open a text file ?
FileObject = open(<filename>)
No translations are required. OR
More secure. FileObject = open(<filename>,<mode>)
Difference between Text files and Binary
Files: Path toa Mode of at
Text Files Binary Files Examples:
Text files stores Binary files are used open ("myfile .txt" 'r')
information in to store binary data F= open
ASCII characters. such as images, Desktop \\ Text File .txt", "r" )
audio, video and open (r "C: \ Users\sony \
text. Desktop \ TextFi1e. txt" ,
58
Question bank - Class Xll (Computer Science)
, Using with statement: In r+ mode, the file In w+ mode, the file
This method is very handy when you have pointer is at the pointer is at the end of
two related operations which you would like beginning of the file. the file.
to execute as a pair , with a block of code in
between. If the file does not If the file does not
Syntax : exists, it will display exist, it will create the
the FileNotFound new file.
with open <FileMode>) as IEwor.
I <File Handle :
f.mite( If the filc exist, it If the file exists, it will
Benefits of usino statevncn(: doesn't show any write the data in the
It automatically closes the file after the nested error. file (overwriting the
previous content).
block of code.
It also handles all the exceptions also
occured before the end of block. Reading Data from a file
Example : open ("Output.txt","w") as f: 1. read() :
f.wHte ("Text") Reads at most n bytes ; if no n is
File Access Modes: specified , reads the entire file.
r —Opens a file for reading only. This is Default Returns the read bytes in the form of a
mode. string.
rb —Opens a file for reading only in Binary Syntax: <Filehandle>.read([n])
format. This is the default mode. 2. readline()
r+ —Opens a file for both reading and writing. Reads a line of input ; if n is specified
I
rb+ —Opens a file for both reading and writing reads at most n bytes.
in binary format. Returns the read bytes in the form of a
w —Opens a file for only. Overwrites the string ending with '\n' character.
file, if already exists, else creates a new file. Returns a blank string if no more bytes
wb —Opens a file for writing only in binary are left for reading in the file.
format. Syntax : <Filehandle>.readline()
wb+ —Opens a file for both reading and writing 3. readlinesO
in binary format. Reads all the lines of a text file.
a —Opens a file for appending. The file pointer is Returns in the form of list.
at the end of the file if the file exists. If the file Syntax : <FileHandle>.readlines()
doesn't exists, it creates a new file for writing.
ab —Opens a file for appending in binary format. Writing data in a File.
a+ —Opens a file for both appending and reading. While writing data in a file : --- > If file
ab+ —Opens a file for both appendingand doesn't exists, it will create the new file.
reading in binary format. If file exists, it will write the data in the file.
Difference between r+ and w+ mode 1. write(string)
r+ mode w+ mode write( ) method takes a string and writes
Used for both reading W+ mode is also used it in the file.
and writing. for both reading and
writin .
Question bank - ClassXll (Computer Science) 59
, For storing data.
VOLchar-actct, • Audio files: .mp3, .mka, .aac etc.
have to add '\n' character to
the end of • Archiye filee .7ip. .rar, .iso. .77 etc.
the string.
For storing numcnc • Vxecutab!e files: .exe. .dl!. .clags etc.
we have to We can open •ome binary files in the
either convclt it into sting using
) or text editor hut we can't read the
NATite
in quotes..
2. content pre«ent inside the file.
I hat's becauqe all the binary files will he
) method is used to "Tite
encoded in the binary format, which can
sequence data in a file(stnng.list be understoodonly by a computeror a
and tuple etc.)
machine.
-Appcndinc data to a filc
In binary files, there is no delimiter to end
Append means to add the data at the end
a line.
of file using 'a' mode.
Since they are directly in the form of
If file doesn't exists, it NOIIcreate the new
binary, hence there is no need to translate
file.
them.
If file exists, it append the data at the That's why these files are easy and fast in
end of a file. .%hcaUÅxorking.
Closina Files : H)icklino refers to the process of converting
A close() function breaks the link of file - the structure (such as list or dictionary) to a
object and the file on the disk. byte stream before w-rit@æåothe file.
After close(), no tasks can be performedon ÄJnpickling rees to the process of
that file through file object or file —handle. converting the byte stream back to the
Syntax : <FileHandle>.close() original structure.
Example: F.close() pickle.dump() : Used to WI-itethe object in a
file.
Path : The full name of a file or directory or Syntax:
folder consists of path. Path is a sequence of pickle.dump(<Strueture>,FileObject)
directory names which give you the hierarchy to Where, Structure can be any
access a particular directory or file name. sequence of Python. It can be either list or
Absolute Path:—) // dictionary.
The absolute paths are from the topmost FileObjeet is the file handle of the
level of directory structure. file, in which we want to WI-ite.
Relative Path : pickle.load() : Used to read the data from a
The relative paths are relative to the current file.
working directory, denoted as a dot (.) , while Syntax: Structure
its parent directory is denoted with two pickle.load(FileObject)
dots(.,) Where, Structure can be any sequence of
Binary Files : Python. It can be either list or dictionary.
Most of the files that we see in our File()bject is the file handle of the file, in
computer system are called binary files. which we want to mite.
Example: Random Access in Files: 1. seek() : seek()
• Image files: .png, .jpg, .gif, -bmp etc. function is used to change the position of the file
• Video files: .mp4, .3gp, .mkv, .avi etc.
Question bank - Class Xll (Computer Science)