CH 5.
File Handling
CBSE – CLASS – XII
COMPUTER SCIENCE WITH PYTHON (NEW)
(SUBJECT CODE : 083)
2
Objective
What is file and why do we need file?
To Learn how to handle files in Python.
How to store data in an organized manner.
How to store data permanently.
How to access data faster.
How to search data faster.
How to modify / update data in a file
3
Introduction
File:-
A file is a collection of related data stored in computer storage for
future data retrieval.
Stream: -
A stream is basically a sequence of data. It can be a sequence of
ASCII /Unicode characters or sequence of bytes.
File Handling: File handling refers to reading and writing contents from
a file.
File object/File-handle:A file object is a reference to a file on disk.It
opens and makes it available for a number of different tasks
4
Types of file
Text Files:
Text files are structured as a sequence of lines, where
each line includes a sequence of ASCII or unicode
characters.
Types of file
Binary File:
A binary file are stored in a computer in a sequence of
bytes(0s and 1s).
5
Types of file
TEXT Files
Regular Text files
Delimited Text files
These are text files which store
In these text files ,a specific character is stored to
the text in the same form as
separate the values e.g a tab,or a comma after every
types. These files have extension
value.
as .txt
When a tab is used to separate the values, these are
called TSV files .
When a comma is used to separate the values,these
are called CSV files.
6
Text file Vs Binary file
Text file Binary File
Text files are made up of ASCII/UNICODE Binary files are made up of 0 and 1
character
Human readable and can be open in any text Non human readable which require specific
editor. program to access its contents.
Internal translator required Translator NOT required.
Each line of text is terminated with a special No delimiters are used for a line.
character known as EOL (End of Line)
Text files are less secure Binary files are more secured
Slower than binary files as internal conversion Binary files are faster as no internal conversion
takes place from text to ASCII to binary. takes place.
File extensions are .txt(regular File extension is .dat
text),.csv/.tsv(delimited text)
7
Full forms
1).dat- data file
2).csv- comma separated file
3).tsv-Tab separated file
4).txt-Text file
5)EOL-End of line
8
Note:
1.Files with extension like .txt,.py,csv,.tsv are some examples of
text files
2.Contents of text files are usually separated by
whitespace,but comma(,) and tab(\t) are also commonly
used to separate values in a text files.
3.The default EOL character in python is \n.
9
Opening and closing a file
Purpose of opening a file: read/write
Syntax to open a file:
<fileobject>=open(<file_name>, [<access_mode>] )
Here,
<file_name> : It is a string value that specifies name of the file.
File names are not case sensitive
<access_mode> : it specifies the purpose of opening the file (But it is
optional). The default access mode is “read- r”.
open () : It returns a file object
<file_object> : It is an object/ variable/file handle
10
Opening and closing a file Conti…
Example: f = open("book.txt")
The code above is the same as:
f = open("book.txt", "r") # By default “read mode”
Closing a file:
After performing the operations, the file has to be closed. For this, a close( ) function is used to
close a file.
Syntax:
<file-object>.close( ) Eg: f.close()
Note:when you open a file in read mode,the given file must
exist,otherwise python will raise error-File not found.
11
Two ways to open a file
Using open() method Using with clause
f1=open(“file1.txt”) With open(“file.txt”) as f1:
content=f1.read() content=f1.read()
Print(content) print(content)
Advantage of using with clause:
When file is opened using “with” statement ,it gets closed automatically.We need not to
close the file explicitly.
It handles all the exceptions also occurred before the end of block.
But when a file is opened using open() method,file remains open if we do not close it
explicitly to free up the memory space.
12
Absolute and relative path
What is the need to close the file?
Once we are done with the read/write operations on a
file, it is a good practice to close a file. While closing a file
,the system frees the memory allocated to it.
Python makes sure that any unwritten or unsaved data is
flushed off(written) to the file before it is closed. Hence it is
always advised to close the file once our work is done.
Also,if the object is reassigned to some file,the previous file
is automatically closed.
Note: To check if the file is closed or not: print(f1.closed) #closed is an attribute
Q:What is the difference between close() method and closed attribute?
13
File Access Mode
Text Binary Description File Offset Position
File File
Mod Mode
e
Opens the file in read mode only. It is the Default mode. Beginning of the file
‘r’ ‘rb’ if the file does not exist raises an Error(File not found) .
Opens a file for writing. If the file already exists, all the Beginning of the file
‘w’ ‘wb’ contents will be overwritten. If the file does not exists, a new
file will be created.
Opens a file in append mode. If the file does not exist, a End of the file
‘a’ ‘ab’ new file will be created.
14
File Access Mode Conti…
Text File Binary File Description File Offset Position
Mode Mode
Opens a file in both read and Write Beginning of the file
‘r+’/ ‘+r’ ‘rb+’/ ‘+rb’ mode.File must exist, otherwise error is
raised.
Opens a file in both read and write Beginning of the file
‘w+’/ ‘+w’ ‘wb+’/ ‘+wb’ mode.New File is created if does not
exist.
Read and end of the file
‘a+’/’+a’ ‘ab+’/ ‘+ab’
Append new data
15
Read the data from a text file
Note: 1 character is 1 byte
There are 3 functions to read data from a file.
read([n] ): reads a specified no. of bytes from the file. If no argument or a
negative number is specified, the entire file content is read.
readline([n] ): Reads one complete line. if “n” is specified, reads n bytes but
maximum upto new line character.If no argument or a negative number is
specified ,it reads a complete line and returns string.
readlines([n] ): Reads all lines and returns the lines along with newline
character(\n) as a list of strings.
16
Lab Work
Create and Open a file using open( ) function
Use the read( ), readline( ) or readlines( ) function
Print/access the data
Close the file.
Example:
Let a text file “Book.txt” has the following text:
Python is interactive language.
It is case sensitive language.
It makes the difference between uppercase and lowercase letters.
It is an official language of google.
17
Ex-1: Program using read( ) function
Go to
Path
18
Ex-2: Program using read( ) function
19
Ex-1: Program using readline( ) function
20
Ex-2: Program using readline( ) function
21
Ex-1: Program using readlines( ) function
Introduction to Dada Handling using Python
22
Ex-2: Program using readlines( ) function
23
Write data into a File
"w" - Write - will overwrite any existing content
There are 2 functions to write the data into a file.
write( ):for writing a single string
Syntax: write(string)
writelines( ): for writing a sequence of strings
Syntax: writelines(n) # n is an iterable object like list,tuple etc
24
Write data into a File:write(string)
write( ):Write method takes a string as an argument and writes it to the text file.
It returns the number of characters being written on execution of the write() method.
Also we need to add a newline character(\n) at the end of every sentence to mark the end of
line.
Note:’\n’ is treated as a single character.
If numeric data are to be written to a text file,data need to be converted into string before writing to the
text file either using double quotes or using str() function.
The write function actually writes data onto the buffer.When the close method is executed , the contents
from the buffer are moved to the file located on the permanent storage.
25
Write data into a File:writelines(<iterable object>)
writelines( ): Write all strings in a list or tuple as lines to file.
Unlike write().the writelines() method does not return the number of
characters written in the file.
26
Ex-2: Write ( ) with write mode
Ex-1: Write ( ) with append mode 27
28
LAB Work: Sample File Program
W.A.P to count the number of characters from a file. (Don’t count white
spaces)
Count the number of words in a file.
Count number of lines in a text file.
Count number of vowels in a text file.
Count the number of ‘is’ word in a text file.
W.A.P to take the details of book(name and price) from 29
the user and write the records(5 records) to the text file.
W.A.P to take the details of book(name and price) from 30
the user and write the records(5 records) to the text file.
31
WORKING WITH BINARY FILES
Binary files are used to store binary data such as images, video files, audio files etc.
They store data in the binary format (0’s and1’s) .
In Binary files there is no delimiter for a line.
To open files in binary mode, when specifying a mode, add 'b' to it.
Pickle module can be imported to write or read data in / from a binary file.
Ex1: Write data to a Binary File 32
33
Ex2: Read the data from Binary File
34
Ex3: Read the data from Binary File
35
tell( ) and seek( ) methods
tell( ): It returns the current position of
cursor in file.
36
tell( ) and seek( ) methods
seek(offset) :
Change the cursor position by
bytes as specified by the offset.
37
Significance of File Pointer
File pointer tells the current position in the file where writing and reading will take place (like a
bookmark)
Example:
test= 1 2 , H E L L O
f1=open(“test.txt”, ”r”)
test= 1 2 , H E L L O
ch=f1.read(3) File Pointer
1 2 , H E L L O
F
P
38
File I/O Attributes
Attribute Description
name Returns the name of the file (Including path)
mode Returns mode of the file. (r or w etc.)
Once the file is successfully opened
encoding a file object
Returns is returned.
the encoding Using
format thisfile
of the file object
you can easily access different type of information related to the file. This
information
closed can be obtained by Returns
readingTrue
values of file
if the specific attributes
closed of the
else returns file.
False
39
File I/O Attributes
Attribute Description
name Returns the name of the file (Including path)
mode Returns mode of the file. (r or w etc.)
Once the file is successfully opened
encoding a file object
Returns is returned.
the encoding Using
format thisfile
of the file object
you can easily access different type of information related to the file. This
information
closed can be obtained by Returns
readingTrue
values of file
if the specific attributes
closed of the
else returns file.
False
40
Example of File Attribute
41
File Path
Absolute Path:
Eg: C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32
Relative Path:
Eg: \Python37-32\binary_search.py
Go Back
We all know that the files are kept in directory which are also known as
folders.
Every running program has a current directory. Which is generally a default
directory and python always see the default directory first.
42
Thank You
Dept Of Computer Science