File Handling in Python
Prof. Anand A Bhosle
Department of Information technology
International Institute of Information Technology, I²IT
www.isquareit.edu.in
File
• A file is collection of information/data in a
particular format.
• A file has different extension based on data it
stored in it and format it uses for representing
that data.
• A file is typically stored on a Storage medium
such as Disk(hard Disk).
• A file is stored on a disk at a location(path).
International Institute of Information
Technology, I²IT, P-14, Rajiv Gandhi
Infotech Park, Hinjawadi Phase 1, Pune -
411 057
Phone - +91 20 22933441/2/3 | Website -
File Structure
• Files are Stored in a hierarchical structure like
a tree.
• At top of tree there is a root node.
• A root node branches into multiple partitions
or drives.
• Drives are having folders or directories and
files .
• Directories in turn may have another folders
or files
International Institute of Information
Technology, I²IT, P-14, Rajiv Gandhi
Infotech Park, Hinjawadi Phase 1, Pune -
411 057
Phone - +91 20 22933441/2/3 | Website -
Files
International Institute of Information
Technology, I²IT, P-14, Rajiv Gandhi
Infotech Park, Hinjawadi Phase 1, Pune -
411 057
Phone - +91 20 22933441/2/3 | Website -
C:/Myfile
(Directory)
My Computer
C:(Drive)
A.txt
(Text File)
D:( Drive) E: (Drive)
File Path
• Files can be retrieved or accessed by
traversing through the hierarchical( tree)
structure as shown in above figure.
• So to access a file, we need to traverse from
root node to the node of a file.
• While traversing , we are visiting the nodes in
a sequence to file node is nothing but path or
location of a file.
International Institute of Information
Technology, I²IT, P-14, Rajiv Gandhi
Infotech Park, Hinjawadi Phase 1, Pune -
411 057
Phone - +91 20 22933441/2/3 | Website -
File Path
• In figure shown above three drive are root
nodes.
• A text file is stored on D drive , so we start
traversal from D node.
• To access a a.txt file , we will traverse from
node D to node a.txt .
• So the path of the a.txt is :
D:Myfilea.txt
International Institute of Information
Technology, I²IT, P-14, Rajiv Gandhi
Infotech Park, Hinjawadi Phase 1, Pune -
411 057
Phone - +91 20 22933441/2/3 | Website -
File Path
“D:Myfilea.txt “ character after dot
indicates the extension of the file.
File can have different extension, example .txt,
.pdf , .docx , . pptx.
In above path character() used to separate
the folders or nodes is known as delimiter.
International Institute of Information
Technology, I²IT, P-14, Rajiv Gandhi
Infotech Park, Hinjawadi Phase 1, Pune -
411 057
Phone - +91 20 22933441/2/3 | Website -
Absolute Path
Absolute path is also called complete or full
path.
Absolute path contains path from root node
and all directories and subdirectories that
contains a file
 D:Myfilea.txt path is the example of
absolute path as it contains all nodes from
root node to the a.txt node.
International Institute of Information
Technology, I²IT, P-14, Rajiv Gandhi
Infotech Park, Hinjawadi Phase 1, Pune -
411 057
Phone - +91 20 22933441/2/3 | Website -
Relative Path
• A relative path starts with respect to present
working directory.
• A file can be accessed by using absolute path.
• A relative path is combined with another path
to form a complete path.
Example : C:StudentsMyFolderMyfile.txt
If C:Students is present working directory.
Then MyFoldeMyfile.txt is Relative Path
International Institute of Information
Technology, I²IT, P-14, Rajiv Gandhi
Infotech Park, Hinjawadi Phase 1, Pune -
411 057
Phone - +91 20 22933441/2/3 | Website -
Types of Files
Python Supports two types of files.
ASCII Text Files
Binary Files.
International Institute of Information
Technology, I²IT, P-14, Rajiv Gandhi
Infotech Park, Hinjawadi Phase 1, Pune -
411 057
Phone - +91 20 22933441/2/3 | Website -
ASCII Text Files
In a Text file each character represents a byte.
Each character has an ASCII value associated
with it.
Text files are processed sequentially in
forward direction.
So , text files can perform one operation at a
time(read/write).
Text files can read or write one character at a
time. International Institute of Information
Technology, I²IT, P-14, Rajiv Gandhi
Infotech Park, Hinjawadi Phase 1, Pune -
411 057
Phone - +91 20 22933441/2/3 | Website -
ASCII Text Files
A text file can contain zero or more characters.
A line in a file can have max 255 characters.
A line end with new line character.
New line character is converted to carriage
return.
A file end with special character called End of
file (EOF).
International Institute of Information
Technology, I²IT, P-14, Rajiv Gandhi
Infotech Park, Hinjawadi Phase 1, Pune -
411 057
Phone - +91 20 22933441/2/3 | Website -
ASCII Text Files
• There are two representation of data in text
file.
Internal: integer value will be represented as
number that occupies 2 or 4 bytes of memory
internally.
External : integer value will be represented as
Decimal or hexadecimal string of characters.
International Institute of Information
Technology, I²IT, P-14, Rajiv Gandhi
Infotech Park, Hinjawadi Phase 1, Pune -
411 057
Phone - +91 20 22933441/2/3 | Website -
Binary Files
A binary file contain any type of data , but in a
binary form for storing and processing
purpose.
 a binary file is sequence of bytes.
It is also referred to as character stream.
They are not in human readable form.
All executableprogram are stored in binary
file.
International Institute of Information
Technology, I²IT, P-14, Rajiv Gandhi
Infotech Park, Hinjawadi Phase 1, Pune -
411 057
Phone - +91 20 22933441/2/3 | Website -
Differences
Binary files requires less space than text files.
Text files are human readable whereas binary
file are not human readable.
Text files are less prone to get corrupted as
compare to binary files.
 Example Text Files : a.txt , a.pdf.
Example Binary file : .png , .jpg
International Institute of Information
Technology, I²IT, P-14, Rajiv Gandhi
Infotech Park, Hinjawadi Phase 1, Pune -
411 057
Phone - +91 20 22933441/2/3 | Website -
Opening and Closing Files
• Python has built-in functions to manipulate
files.
The open() Function : to perform any
operation on a file ,file must be opened.
The open() function is used to open a file in
python.
 open() function creates an object , which can
be used to perform different operations on a
file. International Institute of Information
Technology, I²IT, P-14, Rajiv Gandhi
Infotech Park, Hinjawadi Phase 1, Pune -
411 057
Phone - +91 20 22933441/2/3 | Website -
Syntax of open() function
file_obj = open(‘file_name’,mode)
file_obj : Object returned by open() function ,
which is used to perform different operations
on a file. works as a file handle.
file_name : the name of the file that you want
to open.
mode : indicates the mode in which file is to
be opened.example :read, write, append.
International Institute of Information
Technology, I²IT, P-14, Rajiv Gandhi
Infotech Park, Hinjawadi Phase 1, Pune -
411 057
Phone - +91 20 22933441/2/3 | Website -
Access Modes
Access mode is a optional parameter in open
function.
Default access mode in a open function is read
mode.
A file can be accessed in a read or write mode,
but there are multiple combination of these
modes are avaialble.
International Institute of Information
Technology, I²IT, P-14, Rajiv Gandhi
Infotech Park, Hinjawadi Phase 1, Pune -
411 057
Phone - +91 20 22933441/2/3 | Website -
Access Modes
Access
Modes
Meaning File pointer
r Default mode ,opens a file in read only mode . at beginning of file.
rb Opens file read only binary format . at beginning of file.
r+ Both reading and writing at beginning of file.
rb + Reading and writing in in binary format at beginning of file.
w
Write only. If file does not exist, new file created. If file
exist ,contents are over written.
at beginning of file.
wb
Opens file in binary format for writing only. If file does
not exist, new file created. If file exist ,contents are
over written.
at beginning of file.
w+
Opens file for both reading and writing. If file does not
exist, new file created. If file exist ,contents are over
written.
at beginning of file.
International Institute of Information
Technology, I²IT, P-14, Rajiv Gandhi
Infotech Park, Hinjawadi Phase 1, Pune -
411 057
Phone - +91 20 22933441/2/3 | Website -
Basic Operations on Lists
International Institute of Information
Technology, I²IT, P-14, Rajiv Gandhi
Infotech Park, Hinjawadi Phase 1, Pune -
411 057
Phone - +91 20 22933441/2/3 | Website -
Access
Modes
Meaning File pointer
wb+
Opens file in binary format for both reading and
writing. If file does not exist, new file created. If file
exist ,contents are over written.
at beginning of file.
a
Opens a file for appending, if file does not exist it
creates a file.
at the end of file.
ab
Opens a file in binary format for appending, if file
does not exist it creates a file.
at the end of file.
a+
Opens a file for reading and appending , if file does
not exist it creates a file.
at the end of file.
ab+
Opens a file in binary format for reading and
appending , if file does not exist it creates a file.
at the end of file.
File Object
International Institute of Information
Technology, I²IT, P-14, Rajiv Gandhi
Infotech Park, Hinjawadi Phase 1, Pune -
411 057
Phone - +91 20 22933441/2/3 | Website -
open() function returns a file object , file object
is used to perform operations on file, which is
also known as file handle.
File handle is different from file , but it used to
access file and perform operations on it.
Even you can print file object
Example : f = open(‘a.txt’,’r’)
Output:< open file ‘a.txt’, mode ‘r’at 0x02A64574>
The File Object Attributes
International Institute of Information
Technology, I²IT, P-14, Rajiv Gandhi
Infotech Park, Hinjawadi Phase 1, Pune -
411 057
Phone - +91 20 22933441/2/3 | Website -
File object can be used to access information
about files.
The information about file can be obtained using
different attributes of a file object.
fileobj.closed :returns true if file is closed ,false
otherwise.
fileobj.mode : returns mode in which file is
opened.
fileobj.name : returns the name of the file.
The Close() Method.
International Institute of Information
Technology, I²IT, P-14, Rajiv Gandhi
Infotech Park, Hinjawadi Phase 1, Pune -
411 057
Phone - +91 20 22933441/2/3 | Website -
The close() method is used to close the file.
Once file object is closed you can not access a
file.
Python automatically closes a file once file
object is reassigned to different file.
close() method closes a file and releases
resources associated with a file.
Example
International Institute of Information
Technology, I²IT, P-14, Rajiv Gandhi
Infotech Park, Hinjawadi Phase 1, Pune -
411 057
Phone - +91 20 22933441/2/3 | Website -
file = open(‘a.txt’,’r’)
file.close()
print(file.name)
print(file.mode)
print(file.closed)
Output :
a.txt
r
True
Reading and Writing Files
International Institute of Information
Technology, I²IT, P-14, Rajiv Gandhi
Infotech Park, Hinjawadi Phase 1, Pune -
411 057
Phone - +91 20 22933441/2/3 | Website -
f= open('a.txt','w')
s= input('Enter a text to write to a file')
f.write(s)
print('the Contents Written to a file a.txt are')
f.close()
f=open('a.txt','r')
print(f.read())
f.close()
Reading and writing files
International Institute of Information
Technology, I²IT, P-14, Rajiv Gandhi
Infotech Park, Hinjawadi Phase 1, Pune -
411 057
Phone - +91 20 22933441/2/3 | Website -
Output:
Enter a text to write to a file:
Welcome to Python
the Contents Written to a file a.txt are
Welcome to Python
References
International Institute of Information Technology, I²IT, P-14,
Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411
057
Phone - +91 20 22933441/2/3 | Website -
www.isquareit.edu.in | Email - info@isquareit.edu.in
 “Python Programming using Problem Solving
Approach” By Reema Thareja ,Oxford University
Pres.
Thank-You
International Institute of Information Technology, I²IT,
P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1,
Pune - 411 057
Phone - +91 20 22933441/2/3 | Website -
www.isquareit.edu.in | Email - info@isquareit.edu.in
International Institute of Information Technology,
I²IT,
P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase
1, Pune - 411 057.
Phone - +91 20 22933441/2/3
Website - www.isquareit.edu.in
Email - info@isquareit.edu.in

File Handling in Python

  • 1.
    File Handling inPython Prof. Anand A Bhosle Department of Information technology International Institute of Information Technology, I²IT www.isquareit.edu.in
  • 2.
    File • A fileis collection of information/data in a particular format. • A file has different extension based on data it stored in it and format it uses for representing that data. • A file is typically stored on a Storage medium such as Disk(hard Disk). • A file is stored on a disk at a location(path). International Institute of Information Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website -
  • 3.
    File Structure • Filesare Stored in a hierarchical structure like a tree. • At top of tree there is a root node. • A root node branches into multiple partitions or drives. • Drives are having folders or directories and files . • Directories in turn may have another folders or files International Institute of Information Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website -
  • 4.
    Files International Institute ofInformation Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website - C:/Myfile (Directory) My Computer C:(Drive) A.txt (Text File) D:( Drive) E: (Drive)
  • 5.
    File Path • Filescan be retrieved or accessed by traversing through the hierarchical( tree) structure as shown in above figure. • So to access a file, we need to traverse from root node to the node of a file. • While traversing , we are visiting the nodes in a sequence to file node is nothing but path or location of a file. International Institute of Information Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website -
  • 6.
    File Path • Infigure shown above three drive are root nodes. • A text file is stored on D drive , so we start traversal from D node. • To access a a.txt file , we will traverse from node D to node a.txt . • So the path of the a.txt is : D:Myfilea.txt International Institute of Information Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website -
  • 7.
    File Path “D:Myfilea.txt “character after dot indicates the extension of the file. File can have different extension, example .txt, .pdf , .docx , . pptx. In above path character() used to separate the folders or nodes is known as delimiter. International Institute of Information Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website -
  • 8.
    Absolute Path Absolute pathis also called complete or full path. Absolute path contains path from root node and all directories and subdirectories that contains a file  D:Myfilea.txt path is the example of absolute path as it contains all nodes from root node to the a.txt node. International Institute of Information Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website -
  • 9.
    Relative Path • Arelative path starts with respect to present working directory. • A file can be accessed by using absolute path. • A relative path is combined with another path to form a complete path. Example : C:StudentsMyFolderMyfile.txt If C:Students is present working directory. Then MyFoldeMyfile.txt is Relative Path International Institute of Information Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website -
  • 10.
    Types of Files PythonSupports two types of files. ASCII Text Files Binary Files. International Institute of Information Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website -
  • 11.
    ASCII Text Files Ina Text file each character represents a byte. Each character has an ASCII value associated with it. Text files are processed sequentially in forward direction. So , text files can perform one operation at a time(read/write). Text files can read or write one character at a time. International Institute of Information Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website -
  • 12.
    ASCII Text Files Atext file can contain zero or more characters. A line in a file can have max 255 characters. A line end with new line character. New line character is converted to carriage return. A file end with special character called End of file (EOF). International Institute of Information Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website -
  • 13.
    ASCII Text Files •There are two representation of data in text file. Internal: integer value will be represented as number that occupies 2 or 4 bytes of memory internally. External : integer value will be represented as Decimal or hexadecimal string of characters. International Institute of Information Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website -
  • 14.
    Binary Files A binaryfile contain any type of data , but in a binary form for storing and processing purpose.  a binary file is sequence of bytes. It is also referred to as character stream. They are not in human readable form. All executableprogram are stored in binary file. International Institute of Information Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website -
  • 15.
    Differences Binary files requiresless space than text files. Text files are human readable whereas binary file are not human readable. Text files are less prone to get corrupted as compare to binary files.  Example Text Files : a.txt , a.pdf. Example Binary file : .png , .jpg International Institute of Information Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website -
  • 16.
    Opening and ClosingFiles • Python has built-in functions to manipulate files. The open() Function : to perform any operation on a file ,file must be opened. The open() function is used to open a file in python.  open() function creates an object , which can be used to perform different operations on a file. International Institute of Information Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website -
  • 17.
    Syntax of open()function file_obj = open(‘file_name’,mode) file_obj : Object returned by open() function , which is used to perform different operations on a file. works as a file handle. file_name : the name of the file that you want to open. mode : indicates the mode in which file is to be opened.example :read, write, append. International Institute of Information Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website -
  • 18.
    Access Modes Access modeis a optional parameter in open function. Default access mode in a open function is read mode. A file can be accessed in a read or write mode, but there are multiple combination of these modes are avaialble. International Institute of Information Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website -
  • 19.
    Access Modes Access Modes Meaning Filepointer r Default mode ,opens a file in read only mode . at beginning of file. rb Opens file read only binary format . at beginning of file. r+ Both reading and writing at beginning of file. rb + Reading and writing in in binary format at beginning of file. w Write only. If file does not exist, new file created. If file exist ,contents are over written. at beginning of file. wb Opens file in binary format for writing only. If file does not exist, new file created. If file exist ,contents are over written. at beginning of file. w+ Opens file for both reading and writing. If file does not exist, new file created. If file exist ,contents are over written. at beginning of file. International Institute of Information Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website -
  • 20.
    Basic Operations onLists International Institute of Information Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website - Access Modes Meaning File pointer wb+ Opens file in binary format for both reading and writing. If file does not exist, new file created. If file exist ,contents are over written. at beginning of file. a Opens a file for appending, if file does not exist it creates a file. at the end of file. ab Opens a file in binary format for appending, if file does not exist it creates a file. at the end of file. a+ Opens a file for reading and appending , if file does not exist it creates a file. at the end of file. ab+ Opens a file in binary format for reading and appending , if file does not exist it creates a file. at the end of file.
  • 21.
    File Object International Instituteof Information Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website - open() function returns a file object , file object is used to perform operations on file, which is also known as file handle. File handle is different from file , but it used to access file and perform operations on it. Even you can print file object Example : f = open(‘a.txt’,’r’) Output:< open file ‘a.txt’, mode ‘r’at 0x02A64574>
  • 22.
    The File ObjectAttributes International Institute of Information Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website - File object can be used to access information about files. The information about file can be obtained using different attributes of a file object. fileobj.closed :returns true if file is closed ,false otherwise. fileobj.mode : returns mode in which file is opened. fileobj.name : returns the name of the file.
  • 23.
    The Close() Method. InternationalInstitute of Information Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website - The close() method is used to close the file. Once file object is closed you can not access a file. Python automatically closes a file once file object is reassigned to different file. close() method closes a file and releases resources associated with a file.
  • 24.
    Example International Institute ofInformation Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website - file = open(‘a.txt’,’r’) file.close() print(file.name) print(file.mode) print(file.closed) Output : a.txt r True
  • 25.
    Reading and WritingFiles International Institute of Information Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website - f= open('a.txt','w') s= input('Enter a text to write to a file') f.write(s) print('the Contents Written to a file a.txt are') f.close() f=open('a.txt','r') print(f.read()) f.close()
  • 26.
    Reading and writingfiles International Institute of Information Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website - Output: Enter a text to write to a file: Welcome to Python the Contents Written to a file a.txt are Welcome to Python
  • 27.
    References International Institute ofInformation Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website - www.isquareit.edu.in | Email - [email protected]  “Python Programming using Problem Solving Approach” By Reema Thareja ,Oxford University Pres.
  • 28.
    Thank-You International Institute ofInformation Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057 Phone - +91 20 22933441/2/3 | Website - www.isquareit.edu.in | Email - [email protected] International Institute of Information Technology, I²IT, P-14, Rajiv Gandhi Infotech Park, Hinjawadi Phase 1, Pune - 411 057. Phone - +91 20 22933441/2/3 Website - www.isquareit.edu.in Email - [email protected]