0% found this document useful (0 votes)
14 views

Xii Cs File Handling

Uploaded by

ansh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Xii Cs File Handling

Uploaded by

ansh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

File Handling

Chapter – 5
class – XII CS
Bharat Bhushan Mehta
Source-Google
Source-Google
Some students may confused with SAVING?
VARIABLE and FILE
10 |
OUTPUT DEVICE

SECONDARY MEMORY
PRIMARY MEMORY
SAVE/
a WRITE File.txt
10
10
READ

INPUT DEVICE
• Computer Files having name and occupy space on
disk to store related information.
• They are used to permanently store data in a non-
volatile memory (e.g. hard disk, flash disk).
• Variable is also a named location and stores data
but on Primary (Volatile) Memory.
• When we want to read from or write to a file, we
need to open it first. When we are done, it needs
to be closed so that the resources that are tied
with the file are freed.
• Two Types of files – TEXT FILE, BINARY FILE
TEXT FILE
• Stream of ASCII or UTF-8 (Unicode characters) type of
encoding.
• In memory it stores Computer Readable form (binary
form) but appears in Human Readable Form that is why
internal translation or specific encoding takes place.
• Each line is terminated with delimiter EOL character
(i.e. ‘\n’ new line character – Default).
• It can be opened in normal text editor.
• Example:
– Web standards: html, XML, CSS, JSON etc.
– Source code: c, cpp, js, py, java etc.
– Documents: txt, tex, rtf etc.
– Tabular data: csv, tsv etc.
– Configuration: ini, cfg, reg etc.
BINARY FILE
• Stores information in the form of stream of bytes.
• Appears same as stores in memory that is why no internal translation or specific encoding
takes place also not human readable form.
• Faster and Easier as compare to Text File.
• All binary files follow a specific format. We can open some binary files in the normal text
editor but we can’t read the content present inside the file. That’s because all the binary
files will be encoded in the binary format, which can be understood only by a computer or
machine.
• For handling such binary files we need a specific type of software to open it.
• Most of the files that we see in our computer system are called binary files.
• Example:
– Document files: .pdf, .doc, .xls etc.
– Image files: .png, .jpg, .gif, .bmp etc.
– Video files: .mp4, .3gp, .mkv, .avi etc.
– Audio files: .mp3, .wav, .mka, .aac etc.
– Database files: .mdb, .accde, .frm, .sqlite etc.
– Archive files: .zip, .rar, .iso, .7z etc.
– Executable files: .exe, .dll, .class etc.
BASIC OPERATION OF COMPUTER SYSTEM

• INPUTTING
• STORING
• PROCESSING
– Storing
• OUTPUTTING
• CONTROLING
Python File Handling Operations
• Most importantly there are 4 types of operations
that can be handled by Python on files:
– Open
– Write
– Read
– Close
• Other operations include:
– Search
– Update
– Insert
– Delete
Open and Close a File
• File can be opened and closed by using in-built function open( ) and
close( ).
Syntax:
file_object = open(file_name, mode)
• Here, file_name is the name of the file or the location of the file that
needs to be opened, and file_name should have the file extension
included as well like File.txt and attached with file_object.
• The mode in the open function syntax will tell Python as what
operation you want to do on a file.
Syntax:
file_object .close( )
• close( ) function does not requires any argument rather closes
opened file attached with the file object/file handler.
FILE MODE
FILE MODE
Text File Binary File Description
Mode Mode

'r' 'rb' • This is the default mode.


• File must exist, otherwise I/O error occures.

• This Mode Opens file for writing.


'w' 'wb' • If file does not exist, it creates a new file.
• If file exists it truncates the file.

'a' 'ab' • Open file in append mode.


• If file does not exist, it creates a new file.
'+' '+' • This will open a file for reading and writing (updating)

‘rb+’ or • File creates if not exists, if exists con.


‘r+’
‘r+b’ • Reading and Writing operations take place.

'wb+‘ or • Creates a new file. If file already exists, truncates content.


‘w+'
‘w+b’ • Writing and Reading operation can take place.

‘x’, 't' 'tb' • ‘x’ opens a file for exclusive creation in writing. If exists, the operation fails.
• ‘t’ It opens in text mode (Default).
WRITE INTO TEXT FILE

• STEPS TO WRITE OBJECT IN SPECIFIED FILE :


–open TXT file with WRITE file-mode (w)
– INPUT
– [ PROCESS ]
– close specified file
WRITE INTO TEXT FILE
• Two types of write(SAVE) functions available in Python.

Write Syntax Description


Function
write( ) <fileobject>.write (str) Writes data in the form
of string str in a single
line into file linked with
fileobject or filehandle.
writelines( ) <fileobject>.writelines(Lst) Writes all data/lines of
string/multiple strings
separately in one go in
list Lst into the file
linked/attached with
fileobject.
( SOURCE CODE
WRITE( )

OUTPUT
FOLDER

NOTEPAD
SOURCE CODE
WRITE( )
Using LOOP

OUTPUT
SOURCE CODE
WRITELINES( )

OUTPUT
WRITE INTO TEXT FILE using APPEND mode
• Append mode is also writing data by retaining
previous content in the specified file.

Write Syntax Description


Function with
“a” mode
write( ) <fileobject>.write (str) Writes data without
deleting previous content
in the file linked with
fileobject or filehandle.
SOURCE CODE
APPEND

OUTPUT
WRITE MODE (“w”)
vs
APPEND MODE (“a”)

BOF

EOF
with STATEMENT
• with statement in Python is used in exception
handling
• To make the code cleaner and much more
readable. It simplifies the management of common
resources like file streams.
• Important point is that there is no need to
call file.close() when using with statement.
SOURCE CODE
with Statment

OUTPUT
READ FROM TEXT FILE

• STEPS TO READ DATA FROM SPECIFIED FILE :


–open TXT file with READ file-mode (r)
– INPUT ( from FILE to MEMORY)
– [ PROCESS ]
– OUTPUT
– close specified file
READ FROM TEXT FILE
In order to read a file in python, we must open the
fileWrite
in read mode. Syntax Description
Function
There are three ways in which we can read the files
read( ) <fileobject>.read( ) Reads entire file stored in secondary memory
in python. with fileobject or filehandle and sends to
memory.
– read([n])
read(n) <fileobject>.read(n) If n is specified which is number of bytes to
– readline([n]) be read then file handle will read specified
– readlines() number of bytes from its current location of
byte.
Here, n is<fileobj>.readline(n)
readline(n) the number ofReads bytes toofbeinput
a line read.
from specified file. It
restricts to one line per call even if N is more
First, let’s create a sample thantext fileavailable
the bytes as shown below.
in one line.
readlines(n) <fileobj>.readlines(n) Reads all lines of input from specified file and
returns a list.
Source Code – read( ) & read(n)

OUTPUT
Source Code – read( ), readline( ), readlines( )

OUTPUT
READ FILE with “r+” mode

OUTPUT
Expected Questions For Board Exams
on TEXT file
• Find size/length of file in bytes.
• Count and display Letter.
• Count and display Vowel.
• Count and display Space.
• Count and display Words.
• Count and display Lines.
• Count and display Words start with Letter ‘a’.
• Count and display Words end with Letter ‘a’.
• Count and display Words containing Letter ‘a’ .
• Count and display Words “is” and “are” .
BINARY FILE
• Sometimes we need to write and read non-simple
objects like LIST, TUPLE, DISCTIONARIES, SET to and
from the files. Since object have some structure or
hierarchy associated, it’s formation is required to be
maintained while structure. For this purpose, objects
are often serialized (pickle) and then stored in binary
files.
• "Binary" files are any files where the format isn't made
up of readable characters. Binary files can range from
image files like JPEGs or GIFs, audio files like MP3s or
binary document formats like Word or PDF. In Python,
files are opened in text mode by default. To open files
in binary mode, when specifying a mode, add 'b' to it.
PICKLE/UNPICKLE MODULE
• Serialization – it is also called Pickling is the process
of converting Python object hierarchy into stream
of bytes so that it can be written into a file. Pickling
converts object in such a way that it can be
reconstructed in original form when Un-Pickled or
De-Serialized.
• Unpickling – is the inverse of PICKLING where a
byte stream is converted into an object hierarchy.
Unpickling produces the exact replica of the orignal
object.
• To start with we need to import its module first –
import pickle
DUMP/LOAD METHODS
• Steps to work in BINARY FILE –
– Import pickle module (COMMON IN BOTH MODE)
– OPEN Binary File in the required File Mode (R/W)
– PROCESS in Binary File
– CLOSE Binary File
• Steps to WRITE data in file.
– Import pickle (OPEN YOUR BAG)
– OPEN BIN File (TAKE OUT CS Copy)
– Input DATA – assign or input( ) (NOTE DOWN bb work)
– dump( ) (SAVE command) (Hand/dump write down)
– CLOSE BIN FILE (CLOSE note book)
• Steps to READ data in file.
OPEN/CREATING BINARY FILE
• Open ( ) function is used to open binary file.
• Syntax –
File_Object = open(“file_nm”, file_mode)
• Example –
File = open(“student.dat”, “wb+”)
here student.dat (student.data) file is opened in
Write and Read binary mode.
File = open(“student.dat”, “rb”)
here student.dat (student.data) file is opened in
Read binary mode onlyS.
BASIC OPERATIONS ON BINARY FILE
• WRITE
• READ
• APPEND
• SEARCH
• UPDATE
• INSERT
• DELETE
COMMON STEPS
• STEPS FOR INPUT/PROCESS/OUTPUT :
– import pickle MODULE
– open BIN file with file-mode (r/w/a)
– INPUT
– [ PROCESS ]
– [ OUTPUT ]
– close specified file
WRITE OBJECT INTO FILE

• STEPS TO WRITE OBJECT IN SPECIFIED FILE :


– import pickle MODULE
– open BIN file with WRITE file-mode
– INPUT object
– SAVE object in Secondary Device
– close specified file
SOURCE CODE
ASSIGN

OUTPUT
c SOURCE CODE
User’s Entry

OUTPUT
READ OBJECT FROM FILE
• STEPS TO READ OBJECT FROM SPECIFIED FILE :
– import pickle MODULE
– open BIN file with READ file-mode
– TRANSFER object from FILE to MEMORY
– OUTPUT
– close specified file
SOURCE CODE
ASSIGN

OUTPUT
SOURCE CODE
User’s Entry

OUTPUT
APPEND OBJECT INTO FILE

• STEPS TO APPEND OBJECT FROM SPECIFIED FILE:


– import pickle MODULE
– open BIN file with APPEND file-mode
– INPUT object
– SAVE object in Secondary Device AT THE END of
file
– close specified file
SOURCE CODE
User’s Entry
APPENDED

OUTPUT
SOURCE CODE
User’s Appended
Entry

OUTPUT
SEARCH RECORD INTO FILE

• STEPS TO SEARCH A RECORD FROM FILE:


– import pickle MODULE
– open BIN file with READ file-mode
– INPUT
– READ all records sequentially from BOF
Searching Key Value(s)
– DISPLAY record if FOUND
– close specified file
SOURCE CODE
SEARCH

OUTPUT
Questions on BINARY file
• Read file Student.dat and do following –
– Count those records of students of class XII who
have scored marks between 33 to 60.
– Increase marks by 5 for the student of Roll No. 12.
– Find position of current record.
– Read and display second last record from the file.
UPDATE RECORD INTO FILE
• STEPS TO UPDATE A RECORD FROM FILE:
– import pickle MODULE
– open BIN file with READ & WRITE file-mode
– INPUT (k/board) value to be UPDATED
– STORE position of each record before Read by
Random File Pointer Accessor Function.
– SEARCH all records sequentially from BOF
– if FOUND then reposition file-pointer and
UPDATE
– close specified file
RANDOM FILE POINTER ACCESSER FUNCTION
tell( )
• TO KNOW THE CURRENT POSITION OF FILE POINTER –
tell( ) function returns the current position of file pointer in
the specified file.
Syntax : <file-object>.tell( )
Example :
RANDOM FILE POINTER ACCESSER FUNCTION
seek( )
• TO PLACE FILE-POINTER AT DESIRED POSITION IN THE
FILE–
seek( ) changes the position of file pointer by placing
at specified position in the file.
Syntax :
<file-object>.seek(offset[, mode] )
offset–number which specifying byte number
mode– 0, 1 and 2 number signifies
0 – Beginning of File (Default).
1 – Current position of file-pointer.
2 – End of File.
RANDOM FILE POINTER ACCESSER FUNCTION
seek( )
OUTPUT
SOURCE CODE
UPDATE RECORD
Expected Questions For Board Exams
on BINARY file
• Find Numer of records of specified bin file.
• Search a record based on given value in the file.
• Add a new record after getting values from user.
• Update value with given value in the record in the
file specified.
• Copy all records of a particular value from one into
another file.
• Insert a new record at appropriate position in the
file.
• Delete record based on given value from the file.
WORKING WITH CSV FILE
• Text delimited files that stores tabular data (rows
& col as in DBMS & XLS).
• Most popular and Default delimiter is comma (,)
others are Tab (\t), Colon (:), semi-colon (;) and
pipe (|) character.
• Easy to create and popular for Records handling.
• Preferred export and import format for DBMS &
XLS.
• Can stores Large Amount of Data.
• Has extension File.csv
Open/Close CSV File
• Specify extension .csv
• Open file like other text file, can provide no EOL
translation.
fout = open(“Student.csv”, “w”, newline = “ ”)
fin = open(“Student.csv”, “r”, newline = “ ”)
• Close CSV file
fout.close( )
fin.close( )
WORKING WITH CSV FILE
• Provides conversion of user’s data into writable
form and then stores into csv file.
• Some functions are –
Functions Description
csv . writer( ) Returns a writer object which writes data
into CSV file.
<writerobj>.writerow( ) Writes one row of data onto the writer
object, which then stores in csv file.
<writerobj>.writerows( ) Writes multiple rows of data onto the
writer object, which then stores in csv
file.
WORKING WITH CSV FILE
• Provides conversion of user’s data into readable
form from csv file after parsing (removing
delimition) data into inerrable form (List, Tuple
etc).
• Some functions are –
Functions Description
csv . reader( ) Returns a reader object which reads data
into CSV file.
<readerobj>.readrow( ) Reads one row of data onto the read
object, which then stores in csv file.
<readerobj>.readrows( ) Reads multiple rows of data onto the
reader object, which then stores in csv
file.
WORKING OF CSV WRITER & READER

PRIMARY MEMORY Delimited


Data
User SAVE/
CSV conversion
WRITE
takes place
Data

CSV file on
INPUT DEVICE storage disk

You might also like