SlideShare a Scribd company logo
2
Most read
3
Most read
21
Most read
Akhil Kaushik
Asstt. Prof., CE Deptt.,
TIT Bhiwani
File Handling
What is a File?
• A file represents a sequence of bytes on disk,
where a group of related data is stored.
• File is ready-made structure.
• File is created for permanent data storage (HDD).
• Syntax: file_object = open("filename", "mode")
File Modes
• r – opens a file in reading mode.
• w – opens/ creates a file in writing mode.
• x - opens a file for exclusive creation. If the file
already exists, the operation fails.
• a - opens a file in append mode.
• t - opens in text mode. (default)
• b - opens in binary mode.
• + - opens a file for updating (reading and writing)
File Modes
• In ‘append mode’, previous contents of file remain
& we can write more data after it (if file exists).
• In ‘write mode’, previous contents are cleared &
user writes from scratch(if file exists).
• A ‘Binary File’ is similar to text file. It deals with
non-text files like images or executable files..
Opening Files in Python
• Python has a built-in open() function to open a file.
• This function returns a file object, also called a
handle, as it is used to read or modify the file
accordingly.
• Ex: f = open("test.txt") #file in current directory
• f = open("C:/Python38/README.txt") # specifying
full path of file
Opening Files in Python
• f = open(“raw.txt") # equivalent to 'r' or 'rt'
• f = open(“raw.txt",'w') # write in text mode
• f = open("img.png",'r+b') # read and write in binary
mode
• f= open(“raw.txt","w+") #read and write permissions
Create a Text File
• f = open(“raw.txt","w+")
• Here, f is a variable to open a file.
• open() function is used here.
• raw.txt is a text file that has name ‘raw’.
• Permission is read and write.
• If file does not exist, file will be created.
Writing in a File
Reading from a File
• f = open(“raw.txt", 'r', encoding = 'utf-8')
• f.read(4) # read the first 4 data
• f.read(4) # read the next 4 data
• f.read() # read in the rest till end of file
• f.readline() #read individual lines of a file
Reading from a File
Reading from a File
Reading from a File
Read the whole file line by line:
Random Access - File
• There is no need to access the records of file
sequentially.
• To random access the files, there are 3 functions:
• f.seek()
• f.tell()
Random Access - Files
• It is used to seek pointer position in file at specified
byte. Its syntax is->
seek(offset, from = SEEK_SET)
• Changes the file position to offset bytes, in reference to
from (start, current, end).
• f.tell() – It returns value of current position in file. The value
is count from beginning of file. Its syntax-
f.tell()
Other Functions
• fileno() - Returns an integer number (file descriptor) of
the file.
• flush() – Flushes the write buffer of the file stream.
• seekable() - Returns True if the file stream supports
random access.
• truncate(size=None) - Resizes the file stream to size
bytes. If size is not specified, resizes to current
location.
• writable() - Returns True if the file stream can be
written to.
Close a File
• When we are done with performing operations on
the file, we need to properly close the file.
• Closing a file will free up the resources that were
tied with the file. It is done using the close()
method available in Python.
• Python has a garbage collector to clean up
unreferenced objects but we must not rely on it to
close the file.
Close a File
Close a File
• This method is not entirely safe.
• If an exception occurs when we are performing
some operation with the file, the code exits without
closing the file.
• A safer way is to use a try...finally block.
Close a File
• This way, we are guaranteeing that the file is
properly closed even if an exception is raised that
causes program flow to stop.
• The best way to close a file is by using the with
statement.
• We don't need to explicitly call the close() method. It
is done internally.
File Handling using Colab
• Upload the file:-
• Write from Colab:-
Akhil Kaushik
akhilkaushik05@gmail.com
9416910303
CONTACT ME AT:
Akhil Kaushik
akhilkaushik05@gmail.com
9416910303
THANK YOU !!!

More Related Content

What's hot (20)

ODP
Python Modules
Nitin Reddy Katkam
 
PPTX
Packages In Python Tutorial
Simplilearn
 
PPTX
Python Exception Handling
Megha V
 
PPTX
Python: Modules and Packages
Damian T. Gordon
 
PDF
Python exception handling
Mohammed Sikander
 
PPTX
Data Structures in Python
Devashish Kumar
 
PDF
input/ output in java
sharma230399
 
PPTX
MULTI THREADING IN JAVA
VINOTH R
 
PPTX
Functions in c++
Rokonuzzaman Rony
 
PPTX
Functions in python slide share
Devashish Kumar
 
PPTX
Static Data Members and Member Functions
MOHIT AGARWAL
 
PPTX
Regular expressions in Python
Sujith Kumar
 
PPTX
Modules in Python Programming
sambitmandal
 
PPT
Exception handling and function in python
TMARAGATHAM
 
PPTX
Java package
CS_GDRCST
 
PPTX
Python-Inheritance.pptx
Karudaiyar Ganapathy
 
PPTX
Java(Polymorphism)
harsh kothari
 
PDF
Lesson 02 python keywords and identifiers
Nilimesh Halder
 
PPTX
Method overloading
Lovely Professional University
 
Python Modules
Nitin Reddy Katkam
 
Packages In Python Tutorial
Simplilearn
 
Python Exception Handling
Megha V
 
Python: Modules and Packages
Damian T. Gordon
 
Python exception handling
Mohammed Sikander
 
Data Structures in Python
Devashish Kumar
 
input/ output in java
sharma230399
 
MULTI THREADING IN JAVA
VINOTH R
 
Functions in c++
Rokonuzzaman Rony
 
Functions in python slide share
Devashish Kumar
 
Static Data Members and Member Functions
MOHIT AGARWAL
 
Regular expressions in Python
Sujith Kumar
 
Modules in Python Programming
sambitmandal
 
Exception handling and function in python
TMARAGATHAM
 
Java package
CS_GDRCST
 
Python-Inheritance.pptx
Karudaiyar Ganapathy
 
Java(Polymorphism)
harsh kothari
 
Lesson 02 python keywords and identifiers
Nilimesh Halder
 
Method overloading
Lovely Professional University
 

Similar to File Handling Python (20)

PPTX
pp5-filehandling- python 200824063109 (1).pptx
DrVikasMahor
 
PPTX
this is about file concepts in class 12 in python , text file, binary file, c...
Primary2Primary2
 
PPTX
Chapter - 5.pptx
MikialeTesfamariam
 
PPTX
File Operations in python Read ,Write,binary file etc.
deepalishinkar1
 
PPTX
pspp-rsk.pptx
ARYAN552812
 
PPTX
Data File Handling in Python Programming
gurjeetjuneja
 
PPTX
file handling in python using exception statement
srividhyaarajagopal
 
PPTX
DFH PDF-converted.pptx
AmitKaur17
 
PPTX
Unit V.pptx
ShaswatSurya
 
PDF
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
vsol7206
 
PPTX
FILE HANDLING COMPUTER SCIENCE -FILES.pptx
anushasabhapathy76
 
PPTX
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
PPTX
File Handling in Python -binary files.pptx
deepa63690
 
PPTX
5-filehandling-2004054567151830 (1).pptx
lionsconvent1234
 
PDF
File handling with python class 12th .pdf
lionsconvent1234
 
PPTX
for interview this ppt is a teching aid for file handling concepts includes t...
Primary2Primary2
 
PDF
lecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnj
MrProfEsOr1
 
PPTX
Python IO
RTS Tech
 
PPT
Python File functions
keerthanakommera1
 
PPTX
Python files / directories part15
Vishal Dutt
 
pp5-filehandling- python 200824063109 (1).pptx
DrVikasMahor
 
this is about file concepts in class 12 in python , text file, binary file, c...
Primary2Primary2
 
Chapter - 5.pptx
MikialeTesfamariam
 
File Operations in python Read ,Write,binary file etc.
deepalishinkar1
 
pspp-rsk.pptx
ARYAN552812
 
Data File Handling in Python Programming
gurjeetjuneja
 
file handling in python using exception statement
srividhyaarajagopal
 
DFH PDF-converted.pptx
AmitKaur17
 
Unit V.pptx
ShaswatSurya
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
vsol7206
 
FILE HANDLING COMPUTER SCIENCE -FILES.pptx
anushasabhapathy76
 
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
File Handling in Python -binary files.pptx
deepa63690
 
5-filehandling-2004054567151830 (1).pptx
lionsconvent1234
 
File handling with python class 12th .pdf
lionsconvent1234
 
for interview this ppt is a teching aid for file handling concepts includes t...
Primary2Primary2
 
lecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnj
MrProfEsOr1
 
Python IO
RTS Tech
 
Python File functions
keerthanakommera1
 
Python files / directories part15
Vishal Dutt
 
Ad

More from Akhil Kaushik (20)

PPT
Symbol Table, Error Handler & Code Generation
Akhil Kaushik
 
PPTX
Code Optimization
Akhil Kaushik
 
PPTX
Parsing in Compiler Design
Akhil Kaushik
 
PPTX
Context Free Grammar
Akhil Kaushik
 
PPTX
Error Detection & Recovery
Akhil Kaushik
 
PPTX
Symbol Table
Akhil Kaushik
 
PPTX
Lexical Analyzer Implementation
Akhil Kaushik
 
PPTX
NFA & DFA
Akhil Kaushik
 
PPTX
Lexical Analysis - Compiler Design
Akhil Kaushik
 
PPTX
Regular Expressions
Akhil Kaushik
 
PPTX
Algorithms & Complexity Calculation
Akhil Kaushik
 
PPTX
Intro to Data Structure & Algorithms
Akhil Kaushik
 
PPTX
Decision Making & Loops
Akhil Kaushik
 
PPTX
Basic programs in Python
Akhil Kaushik
 
PPTX
Python Data-Types
Akhil Kaushik
 
PPTX
Introduction to Python Programming
Akhil Kaushik
 
PPT
Compiler Design Basics
Akhil Kaushik
 
PPTX
Bootstrapping in Compiler
Akhil Kaushik
 
PPTX
Compiler construction tools
Akhil Kaushik
 
PPTX
Phases of compiler
Akhil Kaushik
 
Symbol Table, Error Handler & Code Generation
Akhil Kaushik
 
Code Optimization
Akhil Kaushik
 
Parsing in Compiler Design
Akhil Kaushik
 
Context Free Grammar
Akhil Kaushik
 
Error Detection & Recovery
Akhil Kaushik
 
Symbol Table
Akhil Kaushik
 
Lexical Analyzer Implementation
Akhil Kaushik
 
NFA & DFA
Akhil Kaushik
 
Lexical Analysis - Compiler Design
Akhil Kaushik
 
Regular Expressions
Akhil Kaushik
 
Algorithms & Complexity Calculation
Akhil Kaushik
 
Intro to Data Structure & Algorithms
Akhil Kaushik
 
Decision Making & Loops
Akhil Kaushik
 
Basic programs in Python
Akhil Kaushik
 
Python Data-Types
Akhil Kaushik
 
Introduction to Python Programming
Akhil Kaushik
 
Compiler Design Basics
Akhil Kaushik
 
Bootstrapping in Compiler
Akhil Kaushik
 
Compiler construction tools
Akhil Kaushik
 
Phases of compiler
Akhil Kaushik
 
Ad

Recently uploaded (20)

PDF
Week 2 - Irish Natural Heritage Powerpoint.pdf
swainealan
 
PDF
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
PDF
epi editorial commitee meeting presentation
MIPLM
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
Horarios de distribución de agua en julio
pegazohn1978
 
PPTX
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
PDF
STATEMENT-BY-THE-HON.-MINISTER-FOR-HEALTH-ON-THE-COVID-19-OUTBREAK-AT-UG_revi...
nservice241
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PDF
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
PPTX
infertility, types,causes, impact, and management
Ritu480198
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PDF
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PDF
Council of Chalcedon Re-Examined
Smiling Lungs
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PPTX
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
PPTX
How to Create a Customer From Website in Odoo 18.pptx
Celine George
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
Week 2 - Irish Natural Heritage Powerpoint.pdf
swainealan
 
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
epi editorial commitee meeting presentation
MIPLM
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
Horarios de distribución de agua en julio
pegazohn1978
 
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
STATEMENT-BY-THE-HON.-MINISTER-FOR-HEALTH-ON-THE-COVID-19-OUTBREAK-AT-UG_revi...
nservice241
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
infertility, types,causes, impact, and management
Ritu480198
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
Council of Chalcedon Re-Examined
Smiling Lungs
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
Introduction to Biochemistry & Cellular Foundations.pptx
marvinnbustamante1
 
How to Create a Customer From Website in Odoo 18.pptx
Celine George
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 

File Handling Python

  • 1. Akhil Kaushik Asstt. Prof., CE Deptt., TIT Bhiwani File Handling
  • 2. What is a File? • A file represents a sequence of bytes on disk, where a group of related data is stored. • File is ready-made structure. • File is created for permanent data storage (HDD). • Syntax: file_object = open("filename", "mode")
  • 3. File Modes • r – opens a file in reading mode. • w – opens/ creates a file in writing mode. • x - opens a file for exclusive creation. If the file already exists, the operation fails. • a - opens a file in append mode. • t - opens in text mode. (default) • b - opens in binary mode. • + - opens a file for updating (reading and writing)
  • 4. File Modes • In ‘append mode’, previous contents of file remain & we can write more data after it (if file exists). • In ‘write mode’, previous contents are cleared & user writes from scratch(if file exists). • A ‘Binary File’ is similar to text file. It deals with non-text files like images or executable files..
  • 5. Opening Files in Python • Python has a built-in open() function to open a file. • This function returns a file object, also called a handle, as it is used to read or modify the file accordingly. • Ex: f = open("test.txt") #file in current directory • f = open("C:/Python38/README.txt") # specifying full path of file
  • 6. Opening Files in Python • f = open(“raw.txt") # equivalent to 'r' or 'rt' • f = open(“raw.txt",'w') # write in text mode • f = open("img.png",'r+b') # read and write in binary mode • f= open(“raw.txt","w+") #read and write permissions
  • 7. Create a Text File • f = open(“raw.txt","w+") • Here, f is a variable to open a file. • open() function is used here. • raw.txt is a text file that has name ‘raw’. • Permission is read and write. • If file does not exist, file will be created.
  • 9. Reading from a File • f = open(“raw.txt", 'r', encoding = 'utf-8') • f.read(4) # read the first 4 data • f.read(4) # read the next 4 data • f.read() # read in the rest till end of file • f.readline() #read individual lines of a file
  • 12. Reading from a File Read the whole file line by line:
  • 13. Random Access - File • There is no need to access the records of file sequentially. • To random access the files, there are 3 functions: • f.seek() • f.tell()
  • 14. Random Access - Files • It is used to seek pointer position in file at specified byte. Its syntax is-> seek(offset, from = SEEK_SET) • Changes the file position to offset bytes, in reference to from (start, current, end). • f.tell() – It returns value of current position in file. The value is count from beginning of file. Its syntax- f.tell()
  • 15. Other Functions • fileno() - Returns an integer number (file descriptor) of the file. • flush() – Flushes the write buffer of the file stream. • seekable() - Returns True if the file stream supports random access. • truncate(size=None) - Resizes the file stream to size bytes. If size is not specified, resizes to current location. • writable() - Returns True if the file stream can be written to.
  • 16. Close a File • When we are done with performing operations on the file, we need to properly close the file. • Closing a file will free up the resources that were tied with the file. It is done using the close() method available in Python. • Python has a garbage collector to clean up unreferenced objects but we must not rely on it to close the file.
  • 18. Close a File • This method is not entirely safe. • If an exception occurs when we are performing some operation with the file, the code exits without closing the file. • A safer way is to use a try...finally block.
  • 19. Close a File • This way, we are guaranteeing that the file is properly closed even if an exception is raised that causes program flow to stop. • The best way to close a file is by using the with statement. • We don't need to explicitly call the close() method. It is done internally.
  • 20. File Handling using Colab • Upload the file:- • Write from Colab:-