Download as pdf or txt
Download as pdf or txt
You are on page 1of 51

Ch-5

File Handling
Need of File

• To store data in organized


manner
• To store data permanently
• To access data faster
• To search data faster
• To easily modify data later
on
File & File Handling
A file is a sequence of bytes on the
disk/permanent storage where a group of related
data is stored. File is created for permanent
storage of data.
In programming, Sometimes, it is not enough to
only display the data on the console. Those data
are to be retrieved later on,then the concept of file
handling comes. It is impossible to recover the
programmatically generated data again and
again. However, if we need to do so, we may store
it onto the file system which is not volatile and
can be accessed every time. Here, comes the
need of file handling in Python.
File & File Handling
Python has in-built functions to create and
manipulate files. The io module is the default
module for accessing files and you don't need to
import it. The module consists of open(filename,
access_mode) that returns a file object, which is
called "handle". You can use this handle to read
from or write to a file. Python treats the file as an
object, which has its own attributes and methods.
File & File Handling
File handling in Python enables us to
create, update, read, and delete the files
stored on the file system through our
python program. The following operations
can be performed on a file.
In Python, File Handling consists of
following three steps:
Types of File
There are two types of files:
Text Files- A file whose contents can be viewed
using a text editor is called a text file. A text file is
simply a sequence of ASCII or Unicode
characters. Python programs, contents written in
text editors are some of the example of text
files.e.g. .txt,.rtf etc.
Binary Files-A binary file stores the data in the
same way as as stored in the memory. The .exe
files,mp3 file, image files, word documents are
some of the examples of binary files.we
can’t read a binary file using a text editor.e.g.
executable files, images, audio etc.
File & File Handling
Examples of Binary file
File & File Handling
Text files have an End-Of-Line (EOL) character to
indicate each line's termination.
In Python, the new line character (\n) is default
EOL terminator.
Since binary files store data after converting it into
binary language (0s and 1s), there is no EOL
character. This file type returns bytes. This is the
file to be used when dealing with non-text files
such as images or exe.
Difference between Text File
and Binary File
12 ab+
Open a file for both appending and reading in binary format.The file pointer is at the
end of the file if the file exists.The file opens in the append mode .If the file does not
exists,it creates a new file for reading and writing.
Function for file
handling
Opening and Closing File
To perform file operation:
1.A file must be opened first .
2.Then reading, writing, editing
operation can be performed.
3.To create any new file then too it must
be opened.
4.On opening of any file ,a file relevant
structure is created in memory as well
as memory space is created to store
contents.
5. Once we are done working with the
file, we should close the file.
Opening and Closing File
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.
To open a file
File Variable or file handler or file object-
 To handle a data file we need a file
object.
 File object or file handler can be created
by using open() function
 It is a variable which we will use to refer
to the opened file.
 Using this function ,file object is created
which is then used for accessing various
methods and functions available for file
manipulation.
Properties of File handler or
file object
f.name,f.mode,f.closed,f.readable()
the flush() only saves the buffered data to the disk. It doesn't close the file.

To open a file-use open()


Syntax:
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.
*While writing to file the content goes to buffer
and when it is full it is written in the file.
*When file is closed then the unsaved data is
written to the file.
*flush() function is used to force transfer the
data from buffer to the file but it does not closes
Reading from a File
Three different methods are provided to read data
from file.
1.readline(): reads the characters starting from the
current reading position up to a newline character.
2.read() or read(chars): reads the specified
number of characters starting from the current
position.
3.readlines(): reads all lines until the end of file
and returns a list object.
Reading from a File-using read() function
(In argument we will give no of characters)
Reading from a File-using read() function
(In argument we will give no of characters)
Reading from a File-using readline()
function
Reading from a File-using readlines()
function
Reading from a File-using readlines()
function
Reading from a File from different folder
Writing in a file-Write ()
There are two methods to write characters in a file
1.Write(string)-This method takes string as a
parameter and writes it to the file.
Syntax: fileobject.write(string)
While writing using the write() method we must
provide line separator(for eg-’\n’,otherwise entire
data will be written in a single line
*Blinlking cursor indicates successful writing
Writing in a file-Write ()
There are two methods to write characters in a file
2.Writelines(sequence of lines)-For writing a sequence
datatype we use writelines()method.
Because write() method cannot be used to write list,tuple
etc.
Syntax:
fileobject.writelines(sequence)
*For reading or writing cursor always starts from the
beginning.
*writelines() method does not add any EOL,so we have to
use ’\n’after writing every line.
With statement
We can create file by using with statement.
It can be used for group file operation statements within
the block.
It ensures that all the resources allocated to the file object
get deallocated automatically once we stop using the file.
Syntax:
With open() as fileobject:
file manipulation statements
Appending a file-’a’
 It can be add data to an existing file
 For this we use append access mode-’a’
 If a file already exists then it will not be erased and if the
file does not exists the it will be created.
 When the data is written to the file then it will be written
at the end of the file’s current content.
Syntax: fileobject=open(‘filename’,’a’)
Example : F=open(“student.dat,’a’)
Reading from a File-
File Pointer/File handle and read() function

tell() Function:
tell method can be used to get the position of file
handle.This method takes no parameters and
returns an integer value .Initially file pointer points
to the beginning of the file.

Position of data 1 2 3 4 5 6 7 8 9 10
Data of file A B C D E F G H I
File handle or
pointer
Reading from a File-
File Pointer/File handle and read() function

f=open(“x.txt”,”r”)-
File pointer will lie at the starting at of the file means zero
position

Position of data 1 2 3 4 5 6 7 8 9 10
Data of file A B C D E F G H I
File handle or
pointer
Reading from a File-
File Pointer/File handle and read() function
f.read(1)File pointer will lie at the starting at of the file
meansof zero
Position data position
1 2 3 4 5 6 7 8 9
Data of file A B C D E F G H I
File handle or
pointer

f.read(3)
Position of data 1 2 3 4 5 6 7 8 9
Data of file A B C D E F G H I
File handle or
pointer
Reading from a File-
File Pointer/File handle and read() function
seek() Function:
Seek() function is used to change the position of
file handle to given specific position.It is a void
function .It will not return any value.
Syntax:
f.seek(offset , from_what ), where f is a file pointer
or file handle
Parameters:
offset-Number of position to move forward
from_what-It defines the point of reference
return-Does not return any value
seek() Function
What a "line" means to your program.
It is entirely possible to make it recognize line
terminators of different types, and even of mixed
types.
In that case, it may be useful to know that:
Lines of Windows text files are terminated by the
two-byte sequence "\r\n",
whereas lines of Unix (including OS X) text files
are terminated by a single newline.
Lines of classic MacOS text files were terminated
by single carriage returns.
Some other systems have other conventions or
support multiple conventions.
seek() Function

seek() Function:
The reference point is selected by the from_what
argument.It accepts three values:
0-sets the reference point at the beginning of the file.We
cannot use negative value
1:sets the reference point at the current file position
2:sets the reference point at the end of the file

*seek() function works only with binary files.


*By default from_what argument is set to 0.
Note: Reference point at current position / end of file
cannot be set in text mode except when offset is equal to
0.
Split() function

This function will convert a string into list. Basically depends upon the
space or any other sign.
# 1Program in python to read each word separately
(Example of Split())
#2Program in python to read entire text file
#3Program in python to append text at the end of
text file
#4Program in python to read each word separately
(Count no. Of words)
#5Program in python to read each word separately
(To show word with maximum length)

You might also like