DAV SDPS PUBLIC SCHOOL,BHADRAK
STD-XII
COMPUTER SCIENCE
CH-4(Data File Handling)
Why there is a need of File
Handling?
Till now what ever the programs we have
done is there any place where my input and
outputs are being stored?
A file in itself is a bunch of bytes(sequence
of characters) stored on some storage
device(may be hard disk, pen drive etc.
where we can store our file).
File helps us to store the data permanently,
which can be retrieved for future use.
Types of Files
Text Files Binary Files CSV Files
Text Files
Stores information in ASCII or Unicode
characters.(text editor characters like notepad)
Each line of text is terminated with a special
character known as EOL(End Of Line).(Enter
key,\n)
Extension for text file is .txt
It is the default mode of file i.e. if among the
above three types nothing is mentioned then
default will be text file.
Binary Files
Contains information in the same format in which
information is held in memory.(1/0)
(If we will open it in text editor we will not be able to
recognize what all are written there)
There is no delimiter for a file.
No translations are required.
These are more secure.(as data is in 0 and 1 form ,so
we will give our notepad file to any one then they will
not be able to understand.)
Binary file in notepad
Difference between Text and
Binary Files
Text File Binary File
1. Text files stores information in 1. Binary files are used to store
ASCII binary data such as Images, audio,
Characters. video and text.
2. Each line of text is terminated 2. There is no delimiter in Binary
with a file.
Special character known as
EOL(End Of Line).
3. Text files are easy to understand 3. Binary files are difficult to
Because files are in human understand.
readable form.
4. Text files are slower than Binary 4. Binary files are faster and easier
files. for a
5. Binary files are having
Methods to open a file
We have two methods to
open a file.
Using open() function
Using with statement
How to open a Text File?
File handle: If for any file I have to perform any
operation like I have to read the file or have to
count the no. of characters in the file in those
cases instead of giving the file name again and
again we can use the file handle to do the same.
File name: Here we have to give the complete
path of our file.
Mode of a File: In which mode we are opening
our file.
The three basic file modes are read(r ),write(w)
and append(a).
Example
For the above example:
Line-1
If I have to open my .txt file in read mode then if my python program and
my text file both are in the same directory then I only have to write my file
name.
Line-2
If I have saved my file on my desktop then I have to give the complete
path.(Right click on file then properties get the path, here single slash will
be there but we are using double slash in our program because as we are
having the text file so for \t will be considered as tab space it will not be
considered as the text file)
But if I have to use single slash then I have to go as LINE-3 in the above
example.
Line-3
So to give single slash we have to precede it with r.
r stands for row string. Row string means what ever the string we are
having treat it as it is ,don’t including its meaning as it is there in Python.
Using with statement
This method 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.
Syntax:
with open(<FileName>,<FileMode>as<File
Handle>:
f.rite()
Benefits of using with
statement
It automatically closes the
file after the nested block of
code.
It also handles all the
exceptions also occurred
before the end of the block.
Closing files
Syntax:
<File Handle>.close()
File Access Modes
r
rb
r+
rb+
w
wb
w+
Wb+
a
ab
a+
ab+
Example
#Method1(Using open()function) with out close()
f=open("myfile.txt","w")
f.write("welcome")
print("data written in a file")
#Here as we have not used the close() so after execution if we
will open the text file we will find no data.So here explicitely we
have close the file using the close function as given below.
#Method1(Using open()function) with close()
f=open("myfile.txt","w")
f.write("welcome")
print("data written in a file")
f.close()
#Now after execution we can see the data in the text file.
Example
#Method2(Using with statement) without close()
with open("file2.txt","w") as f:
f.write("Welcome to My Class of Python")
print("data written in the file")
#Here after run if we will see the text file then we can
see that data is written there though we have not used
the close() and this is the difference between open()
and with statement.
Reading Data From a File
read()
readline()
readlines
Read()
Reads at most n bytes; if no n is
specified, reads the entire file.(n is the
no. of arguments)
Returns the read bytes in the form of a
string.
Syntax:
<Filehandle>.read([n])
Example
f=open("myfile.txt","r")
data=f.read()
print(data)
# this is if my python file and text file both are in the
same location or directory.
Example
f=open("C:\\Users\\LENOVO\\Desktop\\pravati.txt","r")
data=f.read()
print(data)
# this is if my python file and text file both are in
different location or directory.(right click on the file on
the desktop then go to property and copy the path,
then add the text file name at the end of the path and
make each single slash as a double slash)
Example
f=open(r"C:\Users\LENOVO\Desktop\
pravati.txt","r")
data=f.read()
print(data)
#take single slash and add row string(r)
preceding the string.
Example
f=open(r"C:\Users\LENOVO\Desktop\
pravati.txt","r")
data=f.read(3)
print(data)
#as we have taken 3 so it will read only 3
characters and output will be wel. when w are
not passing any value it is reading the entire
file content.
Example
f=open(r"C:\Users\LENOVO\Desktop\pravati.txt","r")
data=f.read(3)
print(data)
Output:
print("Type=",type(data)) wel
Type= <class 'str'>
readline()
Reads a line of input, if n is specify reads at most n
bytes.
Returns the read bytes in the form of a string ending
with ‘\n’
character.
Returns a blank string if no more bytes are left for
reading in the file.
Syntax:
<filehandle>.readline()
Example
f=open("Devi.txt","w")
f.write('''welcome to My class of Python
All the best for your exam
All of u do well in your exam''')
print("data written in a file")
f.close()
Example
f=open("Devi.txt","r")
data=f.readline()
print(data)
Example
f=open("Devi.txt","r")
data=f.readline(15)
print(data)
data=f.readline()
print(data)
Example
f=open("Devi.txt","r")
data=f.readline(55)
print(data)
#Here even if we are not having 55 characters in the
1st line still it will not read the rest characters from
second line instead it will read the no. of characters
present in the 1st line.
Example
f=open("Devi.txt","r")
data=f.readline()
print(data) Output:
data=f.readline() welcome to My class of
Python
print(data)
All the
#Here in the output we can see best
it is for your exam
returning a
newline character .
Example
f=open("Devi.txt","r")
data=f.readline()
Output:
print(data) welcome to My class of
print("Type=",type(data)) Python
Type= <class 'str'>
Readlines()
Reads all the lines of a text file.
Returns in the form of list.
Syntax:
<FileHandle>.readlines
Example
f=open("Devi.txt","r")
data=f.readlines() Output:
['welcome to My class of Python\n', 'All
Print(data) the best for your exam\n', 'All of u do
well in your exam']
#So it returns the output in the form of a list.
Example
f=open("Devi.txt","r")
data=f.readlines()
Output:
for i in data: welcome to My class of Python
print(i)
All the best for your exam
print("Type=",type(data))
All of u do well in your exam
Type= <class 'list'>
How to write data in a file?
Write()
Writelines()
While writing data in a file:
If file doesn’t exist it will create
the new file.
If file exists , it will write the data
in the file.(overwrite)
Write(string)
Write() method takes a string and writes
it in the file.
For storing data with EOL character, we
have to add ‘\n’ character to the end of
the string.
For storing numeric value ,we have to
either convert it into string using str() or
write in quotes.
Example
f=open("Pratiti.txt","w")
f.write("CBSE class -XII")
f.write("\n Computer Science")
f.close()
Writelines(seq)
Writelines() method is used
to write sequence data
types in a
file(string,list,tuple etc.)
f=open("Pratiti.txt","w")
list=["Computer\n","Mathematics","English"]
f.writelines(list)
f.close()
f=open("Pratiti.txt","w")
list=("Computer\n","Mathematics","English“)
f.writelines(list)
f.close()
f=open("STDXII.txt","w")
a=int(input("Enter value of a"))
b=int(input("Enter value of b"))
c=a+b
#print(c)
f.write('\nA='+str(a))
f.write('\tB='+str(b))
f.write('\tAddition='+str(c)+'\n\n')
f.close()
f=open("STDXII.txt",“a")
a=int(input("Enter value of a"))
b=int(input("Enter value of b"))
c=a+b
#print(c)
f.write('\nA='+str(a))
f.write('\tB='+str(b))
f.write('\tAddition='+str(c)+'\n\n')
f.close()
f=open("STDXII.txt","a")
a=int(input("Enter value of a"))
b=int(input("Enter value of b"))
c=a+b
#print(c)
f.write(str(a))
f.write(str(b))
f.write(str(c))
f.close()
Appending data to a file…
Append means to add the data at
the end of file using ‘a’ mode.
If file doesn’t exists, it will create
the new file.
If file exists, it will append the
data at the end of a file.
append()
f=open("Pratiti.txt",“a")
f.write(“All the best")
f.write("\n Dear students")
f.close()
Closing Files
A close() function breaks the link of file-object and the
file on the disk.
After close() ,no tasks can be performed on that file
through file object or file-handle.
Syntax:
<FileHandle>.close()
Example:
f.close()
Difference between r+ and w+ mode
r+ mode w+ mode
Used for both reading and writing w+ mode is also used for
reading and writing.
In this mode, the file pointer is at the In this mode, the file pointer is
beginning of the file. at the end of the file.
If the file does not exists, it will display If the file does not exists, it will
the FileNotFound Error. create the new file.
If the file exists,it doesn’t show any If the file exists, it will write the
error. data in the file(overwriting the
previous content).
Example(If file exist)
f=open(r"C:\Users\LENOVO\Desktop\PPP.txt","r")
print(f.read())
f.close()
#It will read the data from the text file created on the
desktop.
Example(If file does not
exist)
f=open(r"C:\Users\LENOVO\Desktop\
PPP1.txt","r")
print(f.read())
f.close()
#It will show FileNotFound Error
Example(If file exists)
f=open(r"C:\Users\LENOVO\Desktop\PPP.txt","w")
f.write("Python")
f.close()
#Previous data will be overwritten
Example(If file doesn’t
exists)
f=open(r"C:\Users\LENOVO\Desktop\PPP1.txt","w")
f.write("Pravati")
f.close()
#Here I have changed PPP to PPP1 ,in this nam there
is no text file still it will not show any error instead it
will create a new text file in the name PPP1 on the
desktop.
r+ mode( can both read and write)
read()
f=open(r"C:\Users\LENOVO\Desktop\PPP.txt","r+")
print(f.read())
f.close()
#After running the code, pointer will be at the
beginning of the code
Read(),write()
f=open(r"C:\Users\LENOVO\Desktop\
PPP.txt","r+")
print(f.read())
f.write("ABC")
f.close()
Read(),write(),read()
f=open(r"C:\Users\LENOVO\Desktop\PPP.txt","r+")
print(f.read())
f.write("ABC")
print(f.read())
f.close()
#Here when we are using read() after write() it will
not read “ABC” ,as the pointer is at the end of the
string after write(),so when we will execute it, it will
give one empty space.
So for the above problem if we have to read the entire data
after write() we have to move the pointer to the beginning
of the string and for this we have to use seek() function.
f=open(r"C:\Users\LENOVO\Desktop\PPP.txt","r+")
print(f.read())
f.write("ABC")
f.seek(0)
print(f.read())
f.close()
#If we are writing seek(0) , it will take the pointer to
the starting of the string.
w+ mode
f=open(r"C:\Users\LENOVO\Desktop\
PPP.txt","w+")
print(f.read())
f.close()
#After execution of this code data from our file
will be erased because we have opened it in
w+ mode means we have to write some data
but I have not written the data still the
previous data will get erased(overwrite)
f=open(r"C:\Users\LENOVO\Desktop\PPP.txt","w+")
f.seek(0)
print(f.read())
f.close()
#So before reading the file, moving the file pointer to
the beginning ,still it will not read any data as file is
not having any data because when we are using w+
it means data from the file will be removed.
So for this(above) reason in w+mode we have to first write the
data and then we have to read the data. (This is when our text
file is not having any data)
f=open(r"C:\Users\LENOVO\Desktop\PPP.txt","w+")
f.write("XYZ")
print(f.read())
f.close()
#After execution we can see that it is still not reading
the data but if we will open our text file we can see
the data is there this is because when we are using
write() our file pointer is at the end of the data.
Hence for the above problem we have to
move the pointer to the beginning of the data.
f=open(r"C:\Users\LENOVO\Desktop\PPP.txt","w+")
f.write("XYZ")
f.seek(0)
print(f.read())
f.close()
#Here we can see it is reading the data .
Now suppose already we have
some data in our text file
f=open(r"C:\Users\LENOVO\Desktop\PPP.txt","w+")
f.write("XYZ")
f.seek(0)
print(f.read())
f.close()
#Here we can see it is over.
a+ mode
f=open(r"C:\Users\LENOVO\Desktop\PPP.txt","a+")
f.write("XYZ")
f.seek(0)
print(f.read())
f.close()
#It will append the new data with the previous data.