You are on page 1of 27

Computer Science

Class XII
Data File Handling

K K PRATIHASTA
PGT- CS
JAWAHAR NAVODAYA VIDYALAYA BIRAULI DISTT- SAMASTIPUR
Objective
In this video, you'll learn about Python file operations. More specifically, opening a file,
reading from it, writing into it, closing it, and various file methods that you should be
aware of.

1. What does file handling mean?


2. Open a file in Python
 Python open() file method
 File open modes in Python
3. Close a file in Python
 The close() file method
4. Perform Write operation
 The write() file method
5. Perform Read operation
6. Appending to File
7. Binary File operation
8. Set File offset in Python
 Tell() Method and Seek() Method
What does file handling mean?
 We have seen yet only the transient programs. The programs which run for a short period of time and
give some output and after that their data is disappeared. And when we again run those programs
then we have to use new data.
 This is because the data is entered in primary memory which is temporary memory and its data is
volatile.
 Those programs which are persistent i.e. they are always in running or run for a long time then their
data is stored in permanent storage (e.g. hard disk) . If the program is closed or restarted then the
data used will be retrieved.
 For this purpose the program should have the capability to read or write the text files or data files.
These files can be saved in permanent storage.
 The meaning of File I/O (input-output) is to transfer the data from Primary memory to secondary
memory and vice-versa.
What does file handling mean?
 The data stored with in a file is known as persistent data because this data is
permanently stored in the system.
 Python provides reading and writing capability of data files.
 We save the data in the files for further use.
 As you save your data in files using word, excel etc. same thing we can do with
python.
 “A File is a collection of characters in which we can perform read and write
functions. And also we can save it in secondary storage.”
Data File Operations
Following main operations can be done on files -
1.Opening a file
2.Performing operations
1.READ
2.WRITE etc.
3.Closing The File

Beside above operations there are some more operations can be done on files.-
•Creating of Files
•Traversing of Data
•Appending Data into file.
•Inserting Data into File.
•Deleting Data from File.
•Copying of File.
•Updating Data into File.
File Types
File are of two types –
Text File: A text file is sequence of line and line is the sequence of
characters and this file is saved in a permanent storage device. Although in
python default character coding is ASCII but by using constant ‘U’ this can be
converted into UNICODE. In Text File each line terminates with a special
character which is EOL (End Of Line). These are in human readable form and
these can be created using any text editor.

Binary File: Binary files are used to store binary data such as
images, videos audio etc. Generally numbers are stored in binary
files. In binary file, there is no delimiter to end a line. Since they
are directly in the form of binary hence there is no need to
translate them. That’s why these files are easy and fast in working.
Opening and Closing Files-
To perform file operation, it must be opened first then after reading, writing,
editing operation can be performed. To create any new file then too it must be
opened. On opening of any file, a file relevant structure is created in memory as
well as memory space is created to store contents.

Once we are done working with the file, we should close the file. Closing a file
releases valuable system resources. In case we forgot to close the file, Python
automatically close the file when program ends or file object is no longer referenced
in the program. However, if our program is large and we are reading or writing
multiple files that can take significant amount of resource on the system. If we keep
opening new files carelessly, we could run out of resources. So be a good
programmer, close the file as soon as all task are done with it.
Opening & Closing Files
Before any reading or writing operation of any file, it must be opened first
of all. This file object can be created by using open( ) function .
Open( ) function creates a file object, which is used later to access the file using the
functions related to file manipulation.

Its syntax is following -


file object=open ( <file_name>, <access_mode> )
file_name= name of the file ,enclosed in double quotes.
access_mode= Determines the what kind of operations can be performed with file, like
read, write etc.

File accessing modes -


–read(r): To read the file
–write(w): to write to the file
–append(a): to Write at the end of file.
Opening & Closing Files. . .
f=open( "poem.txt“ ) Opened the File
print(f)
<_io.TextIOWrapper name='poem.txt' mode='r' encoding='cp1252'>
f .close() The file is closed.
Here the point is that the file “poem.txt” which is used here is pre built and
stored in the same folder where Python is installed.

A program describing the functions of file handling. Output


f=open( "poem.txt: “ ,'r')
File Name : poem.txt
print( "File Name : “ ,f.name)
File Mode : r
print( "File Mode: “ ,f.mode)
File Readable ? : True
print( "File Readable ?: “ , f.readable())
File Closed or not : False
print( "File Closed or not: “ ,f.closed)
File Closed : True
f.close()
print( "File Closed: “ , f.closed)
Reading a File
f=open( "poem.txt“, r )
data=f .read() A Program to read
print(data) “poem.txt” File.
f .close()
Output
When things go wrong as they sometimes will;
When the road you are trudging seems all uphill;
When the funds are low, and the debts are high;
And you want to smile, but you have to sigh;
When care is pressing you down a bit
Rest if you must, but don't you quit.
stick to the fight when you are hardest hit,
It is when things go wrong that you must not quit.
Reading a File
f=open( "poem.txt“, r )
Reading first 10 characters
data=f .read(10) from the file “poem.txt”
print(data)
Output
f .close()
When thing

1. We can also use readline( ) function which


can read one line at a time from the file.

2. Same readlines( ) function is used to read


many lines.
readline method: Reads and returns one line from the file.

f=open( "poem.txt“, r )
data=f .readline()
print(data)
data=f .readline()
print(data)
f .close()
Output
When things go wrong as they sometimes will;

When the road you are trudging seems all uphill;


readlines method: Reads and returns a list of lines from the file.
f=open( "poem.txt“, r )
data=f .readlines()
print(data)
f .close()
Output
['When things go wrong as they sometimes will;\n',
'When the road you are trudging seems all uphill;\n',
'When the funds are low, and the debts are high;\n',
'And you want to smile, but you have to sigh;\n', 'When
care is pressing you down a bit\n', "Rest if you must,
but don't you quit.\n", 'stick to the fight when you
are hardest hit,\n', 'It is when things go wrong that
you must not quit.']
Writing to a File
We can write characters into file by using following two methods -
1.write (string)
2.writelines (sequence of lines)
write( ) : it takes a sting as argument and adds to the file. We have to use ‘\n’ in string for end of
line character .
writelines ( ) : if we want to write list, tuple into the file then we use writelines ( ) function.
# Program to write data to a file
f=open( “Jnv.txt“, ‘w’ )
f.write("Hello Students\n")
f.write("I am writing data\n")
f.write("to a file\n")
print("Data written successfully")
f.close()
Output
Data written successfully
# Program to write data to a file
f=open( “student.txt“, ‘w’)
for i in range (5):
name=input(“Enter name of student :”)
f .write (name)
f .close()

# Program to write data to a file ,separated lines


f=open( “student.txt“, ‘w’)
for i in range (5):
name=input(“Enter name of student :”)
f .write (name)
f .write(“\n”)
f .close()
writelines ( ) : if we want to write list, tuple into the file then we use writelines ( ) function.

# Program to write data to a file ,separated lines


f=open( “student1.txt“, ‘w’)
List1=[];
for i in range (5):
name=input(“Enter name of student :”)
List1.append(name+’\n’)
f .writelines (List1)
f .close()

If the file has been opened in append


mode(‘a’) to retain the old content.
BINARY FILES OPERATIONS
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.

We will now discuss the four major operations performed using a binary
file such as—
1. Inserting/Appending record in a binary file.
2. Read records from a binary file.
3. Search a record in a binary file.
4. Update a record in a binary file
Operations in Binary File.
• If we want to write structure such as list, dictionary etc and also we
want to read it then we have to use a module in python known as
pickle.
• Pickling means converting structure into byte stream before writing
the data into file.
• And when we read a file then a opposite operation is to be done
means unpickling.
• Pickle module has two methods –
• dump( ) to write
• load( ) to read.
Insert/Append a Record in Binary File
Inserting or adding (appending) a record into a binary file requires importing pickle
module into your program followed by dump() method to write onto the file.

import pickle
mylist = [ 'a', 'b', 'c', 'd‘ ]
f=open( “datafile.txt” , ‘wb‘ )
pickle.dump(mylist, f)
f .close()
Reading a record from a binary file
The following practical implementation illustrates how a record is read from a binary file.
To read Binary file use of load ( ) function -
Searching a record in a binary file
Searching the binary file “datafile" is carried out on the basis of the value entered by
the user. The file is opened in the read-binary mode.
Updating a record in a binary file
Updating a record in the file requires value to be fetched from the user whose value is
to be updated.
RANDOM ACCESS IN FILES USING TELL() AND SEEK()
seek()—seek() function is used to change the position of the file pointer to a given specific
position. The reference point is defined by the "from_what" argument. It can have any of
the three values:
0: sets the reference point at the beginning of the file, which is by default.
1: sets the reference point at the current file position.
2: sets the reference point at the end of the file.

f.seek(20) move the file pointer to 20th byte in the file


f.seek(–10,1) from current position, move 10 bytes backward
f.seek(10,1) from current position, move 10 bytes forward
f.seek(10,0) from beginning of file, move 10 bytes forward

tell()—tell() returns the current position of the file read/write


pointer within the file. Its syntax is:
f.tell() #where f is file pointer
• When you open a file in reading/writing mode, the file pointer
rests at 0th byte.
• When you open a file in append mode, the file pointer rests at last
byte.
RANDOM ACCESS IN FILES USING TELL() AND SEEK() Example
f = open(“jnvynr.txt", 'w')
line = ‘Welcome to JNV Yamunanagar’
f.write(line)
f.close()
OUTPUT
f = open(“jnvynr.txt", 'rb+')
0
print(f.tell())
'Welcome'
print(f.read(7)) # read seven characters
7
print(f.tell())
‘Welcome to JNV Yamunanagar’
print(f.read())
26
print(f.tell())
f.seek(9,0) # moves to 9 position from beginning
‘o JNV’
print(f.read(5))
f.seek(4, 1) # moves to 4 position from current location
‘unana’
print(f.read(5))
f.seek(-5, 2) # Go to the 5th byte before the end
‘nagar’
print(f.read(5))
f.close()

You might also like