SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (20)

Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
TMARAGATHAM
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
Praveen M Jigajinni
 
Tuple in python
Tuple in pythonTuple in python
Tuple in python
Sharath Ankrajegowda
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
baabtra.com - No. 1 supplier of quality freshers
 
Python tuple
Python   tuplePython   tuple
Python tuple
Mohammed Sikander
 
Pattern matching
Pattern matchingPattern matching
Pattern matching
shravs_188
 
single linked list
single linked listsingle linked list
single linked list
Sathasivam Rangasamy
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
Mohammed Sikander
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python Tutorial
Simplilearn
 
Recursive Function
Recursive FunctionRecursive Function
Recursive Function
Harsh Pathak
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in Python
Pooja B S
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
eShikshak
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
shameen khan
 
Python If Else | If Else Statement In Python | Edureka
Python If Else | If Else Statement In Python | EdurekaPython If Else | If Else Statement In Python | Edureka
Python If Else | If Else Statement In Python | Edureka
Edureka!
 
Stacks and Queue - Data Structures
Stacks and Queue - Data StructuresStacks and Queue - Data Structures
Stacks and Queue - Data Structures
Dr. Jasmine Beulah Gnanadurai
 
Python-03| Data types
Python-03| Data typesPython-03| Data types
Python-03| Data types
Mohd Sajjad
 
Linked list
Linked listLinked list
Linked list
KalaivaniKS1
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
Devashish Kumar
 
Conditionalstatement
ConditionalstatementConditionalstatement
Conditionalstatement
RaginiJain21
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
BMS Institute of Technology and Management
 

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
DHARUNESHBOOPATHY
 
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
SanjayKumarMahto1
 
File Handling.pptx
File Handling.pptxFile Handling.pptx
File Handling.pptx
Ananthi Palanisamy
 
Supervised Learning in Cybersecurity
Supervised Learning in CybersecuritySupervised Learning in Cybersecurity
Supervised Learning in Cybersecurity
International Institute of Information Technology (I²IT)
 
File Handling in C Part I
File Handling in C Part IFile Handling in C Part I
File Handling in C Part I
Arpana Awasthi
 
chapter-4-data-file-handlingeng.pdf
chapter-4-data-file-handlingeng.pdfchapter-4-data-file-handlingeng.pdf
chapter-4-data-file-handlingeng.pdf
SyedAhmed991492
 
File handling4.pdf
File handling4.pdfFile handling4.pdf
File handling4.pdf
sulekha24
 
File handling3.pdf
File handling3.pdfFile handling3.pdf
File handling3.pdf
nishant874609
 
file_c.pdf
file_c.pdffile_c.pdf
file_c.pdf
Osmania University
 
Data Structure - Linked List
Data Structure - Linked ListData Structure - Linked List
Data Structure - Linked List
International Institute of Information Technology (I²IT)
 
File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in python
nitamhaske
 
23CS101T PSPP python program - UNIT 5.pdf
23CS101T PSPP python program - UNIT 5.pdf23CS101T PSPP python program - UNIT 5.pdf
23CS101T PSPP python program - UNIT 5.pdf
RajeshThanikachalam
 
File handling for reference class 12.pptx
File handling for reference class 12.pptxFile handling for reference class 12.pptx
File handling for reference class 12.pptx
PreeTVithule1
 
VKS-Python-FIe Handling text CSV Binary.pptx
VKS-Python-FIe Handling text CSV Binary.pptxVKS-Python-FIe Handling text CSV Binary.pptx
VKS-Python-FIe Handling text CSV Binary.pptx
Vinod Srivastava
 
Big Data Technologies
Big Data TechnologiesBig Data Technologies
Big Data Technologies
International Institute of Information Technology (I²IT)
 
Document Type Definition (DTD)
Document Type Definition (DTD)Document Type Definition (DTD)
Document Type Definition (DTD)
International Institute of Information Technology (I²IT)
 
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
ChereLemma2
 
Unit 5 File handling in C programming.pdf
Unit 5 File handling in C programming.pdfUnit 5 File handling in C programming.pdf
Unit 5 File handling in C programming.pdf
SomyaPachauri1
 
file management functions
file management functionsfile management functions
file management functions
vaani pathak
 
Python-File handling-slides-pkt
Python-File handling-slides-pktPython-File handling-slides-pkt
Python-File handling-slides-pkt
Pradyumna Tripathy
 
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
SanjayKumarMahto1
 
File Handling in C Part I
File Handling in C Part IFile Handling in C Part I
File Handling in C Part I
Arpana Awasthi
 
chapter-4-data-file-handlingeng.pdf
chapter-4-data-file-handlingeng.pdfchapter-4-data-file-handlingeng.pdf
chapter-4-data-file-handlingeng.pdf
SyedAhmed991492
 
File handling4.pdf
File handling4.pdfFile handling4.pdf
File handling4.pdf
sulekha24
 
File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in python
nitamhaske
 
23CS101T PSPP python program - UNIT 5.pdf
23CS101T PSPP python program - UNIT 5.pdf23CS101T PSPP python program - UNIT 5.pdf
23CS101T PSPP python program - UNIT 5.pdf
RajeshThanikachalam
 
File handling for reference class 12.pptx
File handling for reference class 12.pptxFile handling for reference class 12.pptx
File handling for reference class 12.pptx
PreeTVithule1
 
VKS-Python-FIe Handling text CSV Binary.pptx
VKS-Python-FIe Handling text CSV Binary.pptxVKS-Python-FIe Handling text CSV Binary.pptx
VKS-Python-FIe Handling text CSV Binary.pptx
Vinod Srivastava
 
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
ChereLemma2
 
Unit 5 File handling in C programming.pdf
Unit 5 File handling in C programming.pdfUnit 5 File handling in C programming.pdf
Unit 5 File handling in C programming.pdf
SomyaPachauri1
 
file management functions
file management functionsfile management functions
file management functions
vaani pathak
 
Python-File handling-slides-pkt
Python-File handling-slides-pktPython-File handling-slides-pkt
Python-File handling-slides-pkt
Pradyumna Tripathy
 
Ad

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

Minimization of DFA
Minimization of DFAMinimization of DFA
Minimization of DFA
International Institute of Information Technology (I²IT)
 
Understanding Natural Language Processing
Understanding Natural Language ProcessingUnderstanding Natural Language Processing
Understanding Natural Language Processing
International Institute of Information Technology (I²IT)
 
What Is Smart Computing?
What Is Smart Computing?What Is Smart Computing?
What Is Smart Computing?
International Institute of Information Technology (I²IT)
 
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?
International Institute of Information Technology (I²IT)
 
Writing Skills: Importance of Writing Skills
Writing Skills: Importance of Writing SkillsWriting Skills: Importance of Writing Skills
Writing Skills: Importance of Writing Skills
International Institute of Information Technology (I²IT)
 
Professional Communication | Introducing Oneself
Professional Communication | Introducing Oneself Professional Communication | Introducing Oneself
Professional Communication | Introducing Oneself
International Institute of Information Technology (I²IT)
 
Servlet: A Server-side Technology
Servlet: A Server-side TechnologyServlet: A Server-side Technology
Servlet: A Server-side Technology
International Institute of Information Technology (I²IT)
 
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
International Institute of Information Technology (I²IT)
 
Cloud Computing
Cloud ComputingCloud Computing
Cloud Computing
International Institute of Information Technology (I²IT)
 
Hypothesis-Testing
Hypothesis-TestingHypothesis-Testing
Hypothesis-Testing
International Institute of Information Technology (I²IT)
 
Data Science, Big Data, Data Analytics
Data Science, Big Data, Data AnalyticsData Science, Big Data, Data Analytics
Data Science, Big Data, Data Analytics
International Institute of Information Technology (I²IT)
 
Types of Artificial Intelligence
Types of Artificial Intelligence Types of Artificial Intelligence
Types of Artificial Intelligence
International Institute of Information Technology (I²IT)
 
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...
International Institute of Information Technology (I²IT)
 
Sentiment Analysis in Machine Learning
Sentiment Analysis in  Machine LearningSentiment Analysis in  Machine Learning
Sentiment Analysis in Machine Learning
International Institute of Information Technology (I²IT)
 
What Is Cloud Computing?
What Is Cloud Computing?What Is Cloud Computing?
What Is Cloud Computing?
International Institute of Information Technology (I²IT)
 
Introduction To Design Pattern
Introduction To Design PatternIntroduction To Design Pattern
Introduction To Design Pattern
International Institute of Information Technology (I²IT)
 
Importance of Theory of Computations
Importance of Theory of ComputationsImportance of Theory of Computations
Importance of Theory of Computations
International Institute of Information Technology (I²IT)
 
Java as Object Oriented Programming Language
Java as Object Oriented Programming LanguageJava as Object Oriented Programming Language
Java as Object Oriented Programming Language
International Institute of Information Technology (I²IT)
 
What Is High Performance-Computing?
What Is High Performance-Computing?What Is High Performance-Computing?
What Is High Performance-Computing?
International Institute of Information Technology (I²IT)
 
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
International Institute of Information Technology (I²IT)
 
Ad

Recently uploaded (20)

UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
May Patch Tuesday
May Patch TuesdayMay Patch Tuesday
May Patch Tuesday
Ivanti
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Developing System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptxDeveloping System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptx
wondimagegndesta
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
Top-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptxTop-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptx
BR Softech
 
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptxReimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
John Moore
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
IT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information TechnologyIT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information Technology
SHEHABALYAMANI
 
IT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information TechnologyIT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information Technology
SHEHABALYAMANI
 
Agentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community MeetupAgentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community Meetup
Manoj Batra (1600 + Connections)
 
Artificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptxArtificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptx
03ANMOLCHAURASIYA
 
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
James Anderson
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
May Patch Tuesday
May Patch TuesdayMay Patch Tuesday
May Patch Tuesday
Ivanti
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Developing System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptxDeveloping System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptx
wondimagegndesta
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
Top-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptxTop-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptx
BR Softech
 
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptxReimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
John Moore
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
IT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information TechnologyIT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information Technology
SHEHABALYAMANI
 
IT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information TechnologyIT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information Technology
SHEHABALYAMANI
 
Artificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptxArtificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptx
03ANMOLCHAURASIYA
 
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
James Anderson
 

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
  翻译: