SlideShare a Scribd company logo
1 of 28
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

More Related Content

What's hot

What's hot (20)

Python strings presentation
Python strings presentationPython strings presentation
Python strings presentation
 
Strings in python
Strings in pythonStrings in python
Strings in python
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
 
File in C language
File in C languageFile in C language
File in C language
 
Java package
Java packageJava package
Java package
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in Python
 
Function in Python
Function in PythonFunction in Python
Function in Python
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
 
Files in java
Files in javaFiles in java
Files in java
 
Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in Python
 
Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
Python-Inheritance.pptx
Python-Inheritance.pptxPython-Inheritance.pptx
Python-Inheritance.pptx
 
Python list
Python listPython list
Python list
 
Data types in python
Data types in pythonData types in python
Data types in python
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
 

Similar to File Handling in Python

Similar to File Handling in Python (20)

file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
1 cs xii_python_file_handling text n binary file
1 cs xii_python_file_handling text n binary file1 cs xii_python_file_handling text n binary file
1 cs xii_python_file_handling text n binary file
 
File Handling.pptx
File Handling.pptxFile Handling.pptx
File Handling.pptx
 
Supervised Learning in Cybersecurity
Supervised Learning in CybersecuritySupervised Learning in Cybersecurity
Supervised Learning in Cybersecurity
 
File Handling in C Part I
File Handling in C Part IFile Handling in C Part I
File Handling in C Part I
 
chapter-4-data-file-handlingeng.pdf
chapter-4-data-file-handlingeng.pdfchapter-4-data-file-handlingeng.pdf
chapter-4-data-file-handlingeng.pdf
 
File handling4.pdf
File handling4.pdfFile handling4.pdf
File handling4.pdf
 
File handling3.pdf
File handling3.pdfFile handling3.pdf
File handling3.pdf
 
file_c.pdf
file_c.pdffile_c.pdf
file_c.pdf
 
Data Structure - Linked List
Data Structure - Linked ListData Structure - Linked List
Data Structure - Linked List
 
File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in python
 
Big Data Technologies
Big Data TechnologiesBig Data Technologies
Big Data Technologies
 
Document Type Definition (DTD)
Document Type Definition (DTD)Document Type Definition (DTD)
Document Type Definition (DTD)
 
File Management and manipulation in C++ Programming
File Management and manipulation in C++ ProgrammingFile Management and manipulation in C++ Programming
File Management and manipulation in C++ Programming
 
file management functions
file management functionsfile management functions
file management functions
 
Python-File handling-slides-pkt
Python-File handling-slides-pktPython-File handling-slides-pkt
Python-File handling-slides-pkt
 
HCII2014 presentation
HCII2014 presentationHCII2014 presentation
HCII2014 presentation
 
python project jarvis ppt.pptx
python project jarvis ppt.pptxpython project jarvis ppt.pptx
python project jarvis ppt.pptx
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
 
File management
File managementFile management
File management
 

More from International Institute of Information Technology (I²IT)

More from International Institute of Information Technology (I²IT) (20)

Minimization of DFA
Minimization of DFAMinimization of DFA
Minimization of DFA
 
Understanding Natural Language Processing
Understanding Natural Language ProcessingUnderstanding Natural Language Processing
Understanding Natural Language Processing
 
What Is Smart Computing?
What Is Smart Computing?What Is Smart Computing?
What Is Smart Computing?
 
Professional Ethics & Etiquette: What Are They & How Do I Get Them?
Professional Ethics & Etiquette: What Are They & How Do I Get Them?Professional Ethics & Etiquette: What Are They & How Do I Get Them?
Professional Ethics & Etiquette: What Are They & How Do I Get Them?
 
Writing Skills: Importance of Writing Skills
Writing Skills: Importance of Writing SkillsWriting Skills: Importance of Writing Skills
Writing Skills: Importance of Writing Skills
 
Professional Communication | Introducing Oneself
Professional Communication | Introducing Oneself Professional Communication | Introducing Oneself
Professional Communication | Introducing Oneself
 
Servlet: A Server-side Technology
Servlet: A Server-side TechnologyServlet: A Server-side Technology
Servlet: A Server-side Technology
 
What Is Jenkins? Features and How It Works
What Is Jenkins? Features and How It WorksWhat Is Jenkins? Features and How It Works
What Is Jenkins? Features and How It Works
 
Cloud Computing
Cloud ComputingCloud Computing
Cloud Computing
 
Hypothesis-Testing
Hypothesis-TestingHypothesis-Testing
Hypothesis-Testing
 
Data Science, Big Data, Data Analytics
Data Science, Big Data, Data AnalyticsData Science, Big Data, Data Analytics
Data Science, Big Data, Data Analytics
 
Types of Artificial Intelligence
Types of Artificial Intelligence Types of Artificial Intelligence
Types of Artificial Intelligence
 
Difference Between AI(Artificial Intelligence), ML(Machine Learning), DL (Dee...
Difference Between AI(Artificial Intelligence), ML(Machine Learning), DL (Dee...Difference Between AI(Artificial Intelligence), ML(Machine Learning), DL (Dee...
Difference Between AI(Artificial Intelligence), ML(Machine Learning), DL (Dee...
 
Sentiment Analysis in Machine Learning
Sentiment Analysis in  Machine LearningSentiment Analysis in  Machine Learning
Sentiment Analysis in Machine Learning
 
What Is Cloud Computing?
What Is Cloud Computing?What Is Cloud Computing?
What Is Cloud Computing?
 
Introduction To Design Pattern
Introduction To Design PatternIntroduction To Design Pattern
Introduction To Design Pattern
 
Importance of Theory of Computations
Importance of Theory of ComputationsImportance of Theory of Computations
Importance of Theory of Computations
 
Java as Object Oriented Programming Language
Java as Object Oriented Programming LanguageJava as Object Oriented Programming Language
Java as Object Oriented Programming Language
 
What Is High Performance-Computing?
What Is High Performance-Computing?What Is High Performance-Computing?
What Is High Performance-Computing?
 
Data Visualization - How to connect Microsoft Forms to Power BI
Data Visualization - How to connect Microsoft Forms to Power BIData Visualization - How to connect Microsoft Forms to Power BI
Data Visualization - How to connect Microsoft Forms to Power BI
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
 
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Modernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaModernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using Ballerina
 
Less Is More: Utilizing Ballerina to Architect a Cloud Data Platform
Less Is More: Utilizing Ballerina to Architect a Cloud Data PlatformLess Is More: Utilizing Ballerina to Architect a Cloud Data Platform
Less Is More: Utilizing Ballerina to Architect a Cloud Data Platform
 
API Governance and Monetization - The evolution of API governance
API Governance and Monetization -  The evolution of API governanceAPI Governance and Monetization -  The evolution of API governance
API Governance and Monetization - The evolution of API governance
 

File Handling in Python

  • 1. File Handling in Python Prof. Anand A Bhosle Department of Information technology International Institute of Information Technology, I²IT www.isquareit.edu.in
  • 2. 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 -
  • 3. 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 -
  • 4. 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)
  • 5. 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 -
  • 6. 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 -
  • 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 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 -
  • 9. 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 -
  • 10. 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 -
  • 11. 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 -
  • 12. 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 -
  • 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 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 -
  • 15. 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 -
  • 16. 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 -
  • 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 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 -
  • 19. 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 -
  • 20. 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.
  • 21. 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>
  • 22. 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.
  • 23. 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.
  • 24. 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
  • 25. 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()
  • 26. 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
  • 27. 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.
  • 28. 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