SlideShare a Scribd company logo
1 of 37
File handling: Need for a data file, Types of file: Text files, Binary files
and CSV (Comma separated values) files.
● Text File: Basic operations on a text file: Open (filename – absolute
or relative path, mode) / Close a text file, Reading and Manipulation
of data from a text file, Appending data into a text file, standard input /
output and error streams, relative and absolute paths.
● Binary File: Basic operations on a binary file: Open (filename –
absolute or relative path, mode) / Close a binary file, Pickle Module –
methods load and dump; Read, Write/Create, Search, Append and
Update operations in a binary file.
● CSV File: Import csv module, functions – Open / Close a csv file,
Read from a csv file and Write into a csv file using csv.reader ( ) and
csv.writerow( ).
CONTENTS AS PER NEW CBSE CURRICULUM
File handling: Need for a data file, Types of file: Text files,
Binary files & CSV Files
● Text File: Basic operations on a text file: Open (filename –
absolute or relative path, mode) / Close a text file.
CONTENTS COVERAGE IN THIS PRESENTATION
Till now whatever programs we have written, the standard input in coming from keyboard and output
is going to monitor i.e. no where data is stored permanent and entered data is present as long as
program is running . After that execution, the programmatically generated data is disappeared. And
when we again run those programs we start with a fresh data.
Why? This is because that data is entered in RAM which is temporary memory and its data is
volatile.
However, if we need to store the data, we may store it onto the permanent storage which is
not volatile and can be accessed every time.. Here, comes the need of file.
Files enables us to create, update, read, and delete the data stored through our python program.
And all these operations are managed through the file systems.
WHY DO WE NEED FILES
Hard
Disk
Program in RAM
(Random Access
Memory)
A file (i.e. data file) is a named place on the disk where a
sequence of related data is stored.
In python files are simply stream of data, so the
structure of data is not stored in the file, along with data.
It contains data pertaining to a specific application, for
later use. The data files can be stored in two It It contains data
pertaining to a specific application, for later use.
2
What is a file in python
TYPES OF FILES
Python allow us to create and manage
three types of file
1. TEXT FILE
2. BINARY FILE
3. CSV FILE
What is Text File?
 Text file stores information in ASCII
OR UNICODE character. In text file everything
will be stored as a character for example if
data is “computer” then it will take 8 bytes
and if the data is floating value like 11237.9876 it
will take 10 bytes.
In text file each like is terminated by special
character called EOL. In text file some
translation takes place when this EOL character is
read or written. In python EOL is ‘n’ or ‘r’ or
combination of both
1. TEXT FILE
What is Binary File?
 It stores the information in the same format
as in the memory i.e. data is stored according to its
data type so no translation occurs.
In binary file there is no delimiter for a new line
Binary files are faster and easier
for a program to read and write than text
files.
Data in binary files cannot be directly read, it can
be read only through python program for
2. BINARY FILE
What is CSV File?
CSV is a simple file format used to store tabular
data, such as a spreadsheet or database.
Files in the CSV format can be easily imported to
and exported from programs that store data in
tabular format.
3. CSV Files
TEXT FILES BINARY FILES CSV FILES
1. Text Files are sequential files 1. A Binary file contain arbitrary binary
data
CSV is a simple file format used to
store tabular data.
2. Text files only stores texts 2 Binary Files are used to store binary
data such as image, video, audio, text
CSV are used to stores data such as a
spreadsheet or database
3. There is a delimiter EOL (End of Line
i.e n)
3. There is no delimiter A comma-separated values file is a
delimited text file that uses a comma
to separate values
4. Due to delimiter text files takes
more time to process. while reading or
writing operations are performed on
file.
4. No presence of delimiter makes files
to process fast while reading or writing
operations are performed on file.
CSV is faster to handle as these are
smaller in size. Moreover CSV is easy
to generate
5. Text files easy to understand
because these files are in human
readable form
5. Binary files are difficult to understand. CSV is human readable and easy to
read manually
Difference Between Text Files, Binary Files & CSV Files
OPENING AND CLOSING FILES
OPENING AND CLOSING FILES
To handle data files in python, we
need to have a file object. Object can be
created by using open() function or file()
function.
To work on file, first thing we do is open
it. This is done by using built in function
open().
Syntax of open() function is
file_object = open(filename [, access_mode]
[,buffering])
OPENING AND CLOSING FILES
open() requires three arguments to work,
first one ( filename ) is the name of the file on secondary
storage media, which can be string constant or a variable.
The name can include the description of path, in case, the
file does not reside in the same folder / directory in which
we are working
The second parameter (access_mode) describes
how file will be used throughout the program. This is an
optional parameter and the default access_mode is
reading.
OPENING AND CLOSING FILES
The third parameter (buffering) is for specifying how much is
read from the file in one read.
When we work with file(s), a buffer (area in memory where
data is temporarily stored before being written to file), is
automatically associated with file when we open the file.
While writing the content in the file, first it goes to buffer and
once the buffer is full, data is written to the file. Also when file is
closed, any unsaved data is transferred to file. flush() function is
used to force transfer of data from buffer to file
OPENING FILE
myfile = open(“story.txt”)
here disk file “story.txt”is loaded in the memory and
its reference is linked to “myfile” object, now python
program will access “story.txt” through “myfile”
object.
here “story.txt” is present in the same folder where
.py file is stored otherwise if disk file to work is in
another folder we have to give full path.
myfile = open(“d:mydatapoem.txt”,”r”)
here we are accessing “poem.txt” file stored in
separate location i.e. d:mydata folder.
at the time of giving path of file we must use double backslash() in place of
single backslash because in python single slash is used for escape
character and it may cause problem like if the folder name is “nitin” and we
provide path as d:nitinpoem.txt then in nitin “n” will become escape
character for new line, SO ALWAYS USE DOUBLE BACKSLASH IN
PATH
Another solution of double backslash is using “r” before the path making
the string as raw string i.e. no special meaning attached to any character
as:
myfile = open(r“d:mydatapoem.txt”,”r”)
OPENING FILE
Absolute Vs Relative PATH
 To understand PATH we must be familiar
with the terms: DRIVE,
FOLDER/DIRECTORY, FILES.
 Our hard disk is logically divided into many
parts called DRIVES like C DRIVE, D DRIVE
etc.
Absolute Vs Relative PATH
 The drive is the main container in which we put
everything to store.
 The naming format is : DRIVE_LETTER:
 For e.g. C: , D:
 Drive is also known as ROOT DIRECTORY.
 Drive contains Folder and Files.
 Folder contains sub-folders or files
 Files are the actual data container.
Absolute Vs Relative PATH
DRIVE
FOLDER
DRIVE
Folders/Subfolders
DRIVE/FOLDER/FILE HIERARCHY
C:
DRIVE
SALES
FOLDER
2018
FOLDER
REVENUE.TXT
FILE
2019
FOLDER
SHEET.XLS
FILE
IT
FOLDER
MEMBERS.DOC
FOLDER
HR
FOLDER
PROD
FOLDER
NOIDA
FOLDER
SEC_8.XLS
FILE
SEC_12.PPT
FILE
DELHI
FOLDER
Absolute Path
 Absolute path is the full address of any file or
folder from the Drive i.e. from ROOT
FOLDER. It is like:
Drive_Name:FolderFolder…filename
 For e.g. the Absolute path
REVENUE.TXT will be
 C:SALES2018REVENUE.TXT
 Absolute path of SEC_12.PPT is
 C:PRODNOIDASec_12.ppt
of file
Relative Path
 Relative Path is the location of file/folder
from the current folder. To use Relative
path special symbols are:
 Single Dot ( . ) : single dot ( . ) refers to current
folder.
 Double Dot ( .. ) : double dot ( .. ) refers to
parent
folder
 Backslash (  ) : first backslash before (.)
and double dot( .. ) refers to ROOT folder.
Relative addressing
C:
DRIVE
SALES
FOLDER
2018
FOLDER
REVENUE.TXT
FILE
2019
FOLDER
SHEET.XLS
FILE
IT
FOLDER
MEMBERS.DOC
FOLDER
HR
FOLDER
PROD
FOLDER
NOIDA
FOLDER
SEC_8.XLS
FILE
SEC_12.PPT
FILE
DELHI
FOLDER
Current working directory
SUPPOSECURRENTWORKING DIRECTORY IS : SALES
WEWANTTO ACCESSSHEET.XLSFILE,THEN RELATIVEADDRESSWILL BE
.2019SHEET.XLS
Relative addressing
C:
DRIVE
SALES
FOLDER
2018
FOLDER
REVENUE.TXT
FILE
2019
FOLDER
SHEET.XLS
FILE
IT
FOLDER
MEMBERS.DOC
FOLDER
HR
FOLDER
PROD
FOLDER
NOIDA
FOLDER
SEC_8.XLS
FILE
SEC_12.PPT
FILE
DELHI
FOLDER
SUPPOSECURRENTWORKING DIRECTORY IS : DELHI
WEWANTTO ACCESSSEC_8.XLS FILE,THEN RELATIVEADDRESSWILL BE
..NOIDASEC_8.XLS
Current working
directory
Getting name of current working
directory
import os
pwd = os.getcwd()
print("Current Directory
:",pwd)
FILE ACCESS MODES
FILE ACCESS MODES
MODE File Opens in
r Text File Read Mode
rb Binary File Read Mode
These are the default modes. The file
pointer is placed at the beginning for reading
purpose, when we open a file in this mode.
FILE ACCESS MODES
MODE File Opens in
r+ Text File Read & Write Mode
rb+ Binary File Read Write Mode
w Text file write mode
wb Text and Binary File Write Mode
w+ Text File Read and Write Mode
wb+ Text and Binary File Read and Write
Mode
a Appends text file at the end of file, if file
does not exists it creates the file.
FILE ACCESS MODES
MODE File Opens in
ab Appends both text and binary files at
the end of file, if file does not exists it
creates the file.
a+ Text file appending and reading.
ab+ Text and Binary file for appending and
reading.
FILE ACCESS MODES - EXAMPLE
For Ex:
f=open(“notes.txt”, ‘r’)
This is the default mode for
a file.
notes.txt is a text file and is
opened in read mode only.
FILE ACCESS MODES - EXAMPLE
For Ex:
f=open(“notes.txt”, ‘r+’)
notes.txt is a text file and is
opened in read and write mode.
FILE ACCESS MODES - EXAMPLE
For Ex:
f=open(“tests.dat ”, ‘rb’)
tests.dat is a binary file and
is opened in read only mode.
FILE ACCESS MODES - EXAMPLE
For Ex:
f=open(“tests.dat”, ‘rb+’)
tests.dat is binary file and is
opened in both modes that is
reading and writing.
FILE ACCESS MODES - EXAMPLE
For Ex:
f=open(“tests.dat”, ‘ab+’)
tests.dat is binary file and is
opened in both modes that is
reading and appending.
close FUNCTION
close FUNCTION
fileobject. close() will be used to close
the file object, once we have finished
working on it. The method will free up all the
system resources used by the file, this means
that once file is closed, we will not be able to
use the file object any more.
For example:
f.close()
THANK YOU &
HAVE A NICE DAY
UNDER THE GUIDANCE OF KVS RO AGRA
VEDIO LESSON PREPARED BY:
KIRTI GUPTA
PGT(CS)
KV NTPC DADRI

More Related Content

What's hot

Price Comparison Website
Price Comparison Website Price Comparison Website
Price Comparison Website Rohit Malhotra
 
Tableau Tutorial For Beginners | Tableau Training For Beginners | Tableau Cer...
Tableau Tutorial For Beginners | Tableau Training For Beginners | Tableau Cer...Tableau Tutorial For Beginners | Tableau Training For Beginners | Tableau Cer...
Tableau Tutorial For Beginners | Tableau Training For Beginners | Tableau Cer...Edureka!
 
Entity Relationship Diagram of Library System
Entity Relationship Diagram of Library SystemEntity Relationship Diagram of Library System
Entity Relationship Diagram of Library SystemAbdul Rahman Sherzad
 
Dax best practices.pdf
Dax best practices.pdfDax best practices.pdf
Dax best practices.pdfdeepneuron
 
Web 3.0 (Presentation)
Web 3.0 (Presentation)Web 3.0 (Presentation)
Web 3.0 (Presentation)Allan Cho
 
Tableau Architecture
Tableau ArchitectureTableau Architecture
Tableau ArchitectureVivek Mohan
 
Library and member management system (lamms) by vikas sharma
Library and member management system (lamms) by vikas sharmaLibrary and member management system (lamms) by vikas sharma
Library and member management system (lamms) by vikas sharmaVikas Sharma
 
How To Convert Your SAP BusinessObjects Unused Licenses To SAP Analytics Cloud
How To Convert Your SAP BusinessObjects Unused Licenses To SAP Analytics CloudHow To Convert Your SAP BusinessObjects Unused Licenses To SAP Analytics Cloud
How To Convert Your SAP BusinessObjects Unused Licenses To SAP Analytics CloudWiiisdom
 
Library Management System
Library Management SystemLibrary Management System
Library Management SystemAnit Thapaliya
 
E farming management system project ppt
E farming management system project pptE farming management system project ppt
E farming management system project pptnandinim26
 
Understand SAP BusinessObjects Licenses & Roadmap
Understand SAP BusinessObjects Licenses & RoadmapUnderstand SAP BusinessObjects Licenses & Roadmap
Understand SAP BusinessObjects Licenses & RoadmapWiiisdom
 
Library management sytem
Library management sytemLibrary management sytem
Library management sytemashu6
 
PROJECT FOR CSE BY TUSHAR DHOOT
PROJECT FOR CSE BY TUSHAR DHOOTPROJECT FOR CSE BY TUSHAR DHOOT
PROJECT FOR CSE BY TUSHAR DHOOTTushar Dhoot
 
Report on online bus management
Report on online bus managementReport on online bus management
Report on online bus managementNaeem Ahmad
 
Tableau online training
Tableau online trainingTableau online training
Tableau online trainingsuresh
 
College Stationery Management System VB 6.0 and Microsoft Access Project
College Stationery Management System VB 6.0  and Microsoft Access ProjectCollege Stationery Management System VB 6.0  and Microsoft Access Project
College Stationery Management System VB 6.0 and Microsoft Access ProjectTushar Soni
 
Online News Portal System
Online News Portal SystemOnline News Portal System
Online News Portal SystemRajib Roy
 
Ip library management project
Ip library management projectIp library management project
Ip library management projectAmazShopzone
 
OBIEE - Introduction & building reports
OBIEE - Introduction & building reportsOBIEE - Introduction & building reports
OBIEE - Introduction & building reportsDeepika Raipuria
 

What's hot (20)

Price Comparison Website
Price Comparison Website Price Comparison Website
Price Comparison Website
 
Tableau Tutorial For Beginners | Tableau Training For Beginners | Tableau Cer...
Tableau Tutorial For Beginners | Tableau Training For Beginners | Tableau Cer...Tableau Tutorial For Beginners | Tableau Training For Beginners | Tableau Cer...
Tableau Tutorial For Beginners | Tableau Training For Beginners | Tableau Cer...
 
Entity Relationship Diagram of Library System
Entity Relationship Diagram of Library SystemEntity Relationship Diagram of Library System
Entity Relationship Diagram of Library System
 
Dax best practices.pdf
Dax best practices.pdfDax best practices.pdf
Dax best practices.pdf
 
Web 3.0 (Presentation)
Web 3.0 (Presentation)Web 3.0 (Presentation)
Web 3.0 (Presentation)
 
Tableau Architecture
Tableau ArchitectureTableau Architecture
Tableau Architecture
 
Online bookshop
Online bookshopOnline bookshop
Online bookshop
 
Library and member management system (lamms) by vikas sharma
Library and member management system (lamms) by vikas sharmaLibrary and member management system (lamms) by vikas sharma
Library and member management system (lamms) by vikas sharma
 
How To Convert Your SAP BusinessObjects Unused Licenses To SAP Analytics Cloud
How To Convert Your SAP BusinessObjects Unused Licenses To SAP Analytics CloudHow To Convert Your SAP BusinessObjects Unused Licenses To SAP Analytics Cloud
How To Convert Your SAP BusinessObjects Unused Licenses To SAP Analytics Cloud
 
Library Management System
Library Management SystemLibrary Management System
Library Management System
 
E farming management system project ppt
E farming management system project pptE farming management system project ppt
E farming management system project ppt
 
Understand SAP BusinessObjects Licenses & Roadmap
Understand SAP BusinessObjects Licenses & RoadmapUnderstand SAP BusinessObjects Licenses & Roadmap
Understand SAP BusinessObjects Licenses & Roadmap
 
Library management sytem
Library management sytemLibrary management sytem
Library management sytem
 
PROJECT FOR CSE BY TUSHAR DHOOT
PROJECT FOR CSE BY TUSHAR DHOOTPROJECT FOR CSE BY TUSHAR DHOOT
PROJECT FOR CSE BY TUSHAR DHOOT
 
Report on online bus management
Report on online bus managementReport on online bus management
Report on online bus management
 
Tableau online training
Tableau online trainingTableau online training
Tableau online training
 
College Stationery Management System VB 6.0 and Microsoft Access Project
College Stationery Management System VB 6.0  and Microsoft Access ProjectCollege Stationery Management System VB 6.0  and Microsoft Access Project
College Stationery Management System VB 6.0 and Microsoft Access Project
 
Online News Portal System
Online News Portal SystemOnline News Portal System
Online News Portal System
 
Ip library management project
Ip library management projectIp library management project
Ip library management project
 
OBIEE - Introduction & building reports
OBIEE - Introduction & building reportsOBIEE - Introduction & building reports
OBIEE - Introduction & building reports
 

Similar to Data file handling in python introduction,opening & closing files

FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.ssuser00ad4e
 
File handling4.pdf
File handling4.pdfFile handling4.pdf
File handling4.pdfsulekha24
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugevsol7206
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++Vineeta Garg
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxarmaansohail9356
 
DFH PDF-converted.pptx
DFH PDF-converted.pptxDFH PDF-converted.pptx
DFH PDF-converted.pptxAmitKaur17
 
File Handling in C Part I
File Handling in C Part IFile Handling in C Part I
File Handling in C Part IArpana Awasthi
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxAshwini Raut
 
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 fileSanjayKumarMahto1
 
File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in pythonnitamhaske
 
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++ ProgrammingChereLemma2
 

Similar to Data file handling in python introduction,opening & closing files (20)

FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.
 
File handling4.pdf
File handling4.pdfFile handling4.pdf
File handling4.pdf
 
File handling3.pdf
File handling3.pdfFile handling3.pdf
File handling3.pdf
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
 
Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
 
Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
 
Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptx
 
DFH PDF-converted.pptx
DFH PDF-converted.pptxDFH PDF-converted.pptx
DFH PDF-converted.pptx
 
FILE HANDLING.pptx
FILE HANDLING.pptxFILE HANDLING.pptx
FILE HANDLING.pptx
 
File Handling in C Part I
File Handling in C Part IFile Handling in C Part I
File Handling in C Part I
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
 
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
 
Python file handling
Python file handlingPython file handling
Python file handling
 
File Handling In C++
File Handling In C++File Handling In C++
File Handling In C++
 
Filesin c++
Filesin c++Filesin c++
Filesin c++
 
File handling and Dictionaries in python
File handling and Dictionaries in pythonFile handling and Dictionaries in python
File handling and Dictionaries in python
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
 
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
 

More from Keerty Smile

Insight into progam execution ppt
Insight into progam execution pptInsight into progam execution ppt
Insight into progam execution pptKeerty Smile
 
Data file handling in python binary & csv files
Data file handling in python binary & csv filesData file handling in python binary & csv files
Data file handling in python binary & csv filesKeerty Smile
 
Data file handling in python reading & writing methods
Data file handling in python reading & writing methodsData file handling in python reading & writing methods
Data file handling in python reading & writing methodsKeerty Smile
 

More from Keerty Smile (7)

Insight into progam execution ppt
Insight into progam execution pptInsight into progam execution ppt
Insight into progam execution ppt
 
Data file handling in python binary & csv files
Data file handling in python binary & csv filesData file handling in python binary & csv files
Data file handling in python binary & csv files
 
Data file handling in python reading & writing methods
Data file handling in python reading & writing methodsData file handling in python reading & writing methods
Data file handling in python reading & writing methods
 
Keerty rdbms sql
Keerty rdbms sqlKeerty rdbms sql
Keerty rdbms sql
 
Computer networks
Computer networksComputer networks
Computer networks
 
Recursion part 2
Recursion part 2Recursion part 2
Recursion part 2
 
Recursion part 1
Recursion part 1Recursion part 1
Recursion part 1
 

Recently uploaded

EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 

Recently uploaded (20)

EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 

Data file handling in python introduction,opening & closing files

  • 1.
  • 2. File handling: Need for a data file, Types of file: Text files, Binary files and CSV (Comma separated values) files. ● Text File: Basic operations on a text file: Open (filename – absolute or relative path, mode) / Close a text file, Reading and Manipulation of data from a text file, Appending data into a text file, standard input / output and error streams, relative and absolute paths. ● Binary File: Basic operations on a binary file: Open (filename – absolute or relative path, mode) / Close a binary file, Pickle Module – methods load and dump; Read, Write/Create, Search, Append and Update operations in a binary file. ● CSV File: Import csv module, functions – Open / Close a csv file, Read from a csv file and Write into a csv file using csv.reader ( ) and csv.writerow( ). CONTENTS AS PER NEW CBSE CURRICULUM
  • 3. File handling: Need for a data file, Types of file: Text files, Binary files & CSV Files ● Text File: Basic operations on a text file: Open (filename – absolute or relative path, mode) / Close a text file. CONTENTS COVERAGE IN THIS PRESENTATION
  • 4. Till now whatever programs we have written, the standard input in coming from keyboard and output is going to monitor i.e. no where data is stored permanent and entered data is present as long as program is running . After that execution, the programmatically generated data is disappeared. And when we again run those programs we start with a fresh data. Why? This is because that data is entered in RAM which is temporary memory and its data is volatile. However, if we need to store the data, we may store it onto the permanent storage which is not volatile and can be accessed every time.. Here, comes the need of file. Files enables us to create, update, read, and delete the data stored through our python program. And all these operations are managed through the file systems. WHY DO WE NEED FILES Hard Disk Program in RAM (Random Access Memory)
  • 5. A file (i.e. data file) is a named place on the disk where a sequence of related data is stored. In python files are simply stream of data, so the structure of data is not stored in the file, along with data. It contains data pertaining to a specific application, for later use. The data files can be stored in two It It contains data pertaining to a specific application, for later use. 2 What is a file in python
  • 6. TYPES OF FILES Python allow us to create and manage three types of file 1. TEXT FILE 2. BINARY FILE 3. CSV FILE
  • 7. What is Text File?  Text file stores information in ASCII OR UNICODE character. In text file everything will be stored as a character for example if data is “computer” then it will take 8 bytes and if the data is floating value like 11237.9876 it will take 10 bytes. In text file each like is terminated by special character called EOL. In text file some translation takes place when this EOL character is read or written. In python EOL is ‘n’ or ‘r’ or combination of both 1. TEXT FILE
  • 8. What is Binary File?  It stores the information in the same format as in the memory i.e. data is stored according to its data type so no translation occurs. In binary file there is no delimiter for a new line Binary files are faster and easier for a program to read and write than text files. Data in binary files cannot be directly read, it can be read only through python program for 2. BINARY FILE
  • 9. What is CSV File? CSV is a simple file format used to store tabular data, such as a spreadsheet or database. Files in the CSV format can be easily imported to and exported from programs that store data in tabular format. 3. CSV Files
  • 10. TEXT FILES BINARY FILES CSV FILES 1. Text Files are sequential files 1. A Binary file contain arbitrary binary data CSV is a simple file format used to store tabular data. 2. Text files only stores texts 2 Binary Files are used to store binary data such as image, video, audio, text CSV are used to stores data such as a spreadsheet or database 3. There is a delimiter EOL (End of Line i.e n) 3. There is no delimiter A comma-separated values file is a delimited text file that uses a comma to separate values 4. Due to delimiter text files takes more time to process. while reading or writing operations are performed on file. 4. No presence of delimiter makes files to process fast while reading or writing operations are performed on file. CSV is faster to handle as these are smaller in size. Moreover CSV is easy to generate 5. Text files easy to understand because these files are in human readable form 5. Binary files are difficult to understand. CSV is human readable and easy to read manually Difference Between Text Files, Binary Files & CSV Files
  • 12. OPENING AND CLOSING FILES To handle data files in python, we need to have a file object. Object can be created by using open() function or file() function. To work on file, first thing we do is open it. This is done by using built in function open(). Syntax of open() function is file_object = open(filename [, access_mode] [,buffering])
  • 13. OPENING AND CLOSING FILES open() requires three arguments to work, first one ( filename ) is the name of the file on secondary storage media, which can be string constant or a variable. The name can include the description of path, in case, the file does not reside in the same folder / directory in which we are working The second parameter (access_mode) describes how file will be used throughout the program. This is an optional parameter and the default access_mode is reading.
  • 14. OPENING AND CLOSING FILES The third parameter (buffering) is for specifying how much is read from the file in one read. When we work with file(s), a buffer (area in memory where data is temporarily stored before being written to file), is automatically associated with file when we open the file. While writing the content in the file, first it goes to buffer and once the buffer is full, data is written to the file. Also when file is closed, any unsaved data is transferred to file. flush() function is used to force transfer of data from buffer to file
  • 15. OPENING FILE myfile = open(“story.txt”) here disk file “story.txt”is loaded in the memory and its reference is linked to “myfile” object, now python program will access “story.txt” through “myfile” object. here “story.txt” is present in the same folder where .py file is stored otherwise if disk file to work is in another folder we have to give full path.
  • 16. myfile = open(“d:mydatapoem.txt”,”r”) here we are accessing “poem.txt” file stored in separate location i.e. d:mydata folder. at the time of giving path of file we must use double backslash() in place of single backslash because in python single slash is used for escape character and it may cause problem like if the folder name is “nitin” and we provide path as d:nitinpoem.txt then in nitin “n” will become escape character for new line, SO ALWAYS USE DOUBLE BACKSLASH IN PATH Another solution of double backslash is using “r” before the path making the string as raw string i.e. no special meaning attached to any character as: myfile = open(r“d:mydatapoem.txt”,”r”) OPENING FILE
  • 17. Absolute Vs Relative PATH  To understand PATH we must be familiar with the terms: DRIVE, FOLDER/DIRECTORY, FILES.  Our hard disk is logically divided into many parts called DRIVES like C DRIVE, D DRIVE etc.
  • 18. Absolute Vs Relative PATH  The drive is the main container in which we put everything to store.  The naming format is : DRIVE_LETTER:  For e.g. C: , D:  Drive is also known as ROOT DIRECTORY.  Drive contains Folder and Files.  Folder contains sub-folders or files  Files are the actual data container.
  • 19. Absolute Vs Relative PATH DRIVE FOLDER DRIVE Folders/Subfolders
  • 21. Absolute Path  Absolute path is the full address of any file or folder from the Drive i.e. from ROOT FOLDER. It is like: Drive_Name:FolderFolder…filename  For e.g. the Absolute path REVENUE.TXT will be  C:SALES2018REVENUE.TXT  Absolute path of SEC_12.PPT is  C:PRODNOIDASec_12.ppt of file
  • 22. Relative Path  Relative Path is the location of file/folder from the current folder. To use Relative path special symbols are:  Single Dot ( . ) : single dot ( . ) refers to current folder.  Double Dot ( .. ) : double dot ( .. ) refers to parent folder  Backslash ( ) : first backslash before (.) and double dot( .. ) refers to ROOT folder.
  • 25. Getting name of current working directory import os pwd = os.getcwd() print("Current Directory :",pwd)
  • 27. FILE ACCESS MODES MODE File Opens in r Text File Read Mode rb Binary File Read Mode These are the default modes. The file pointer is placed at the beginning for reading purpose, when we open a file in this mode.
  • 28. FILE ACCESS MODES MODE File Opens in r+ Text File Read & Write Mode rb+ Binary File Read Write Mode w Text file write mode wb Text and Binary File Write Mode w+ Text File Read and Write Mode wb+ Text and Binary File Read and Write Mode a Appends text file at the end of file, if file does not exists it creates the file.
  • 29. FILE ACCESS MODES MODE File Opens in ab Appends both text and binary files at the end of file, if file does not exists it creates the file. a+ Text file appending and reading. ab+ Text and Binary file for appending and reading.
  • 30. FILE ACCESS MODES - EXAMPLE For Ex: f=open(“notes.txt”, ‘r’) This is the default mode for a file. notes.txt is a text file and is opened in read mode only.
  • 31. FILE ACCESS MODES - EXAMPLE For Ex: f=open(“notes.txt”, ‘r+’) notes.txt is a text file and is opened in read and write mode.
  • 32. FILE ACCESS MODES - EXAMPLE For Ex: f=open(“tests.dat ”, ‘rb’) tests.dat is a binary file and is opened in read only mode.
  • 33. FILE ACCESS MODES - EXAMPLE For Ex: f=open(“tests.dat”, ‘rb+’) tests.dat is binary file and is opened in both modes that is reading and writing.
  • 34. FILE ACCESS MODES - EXAMPLE For Ex: f=open(“tests.dat”, ‘ab+’) tests.dat is binary file and is opened in both modes that is reading and appending.
  • 36. close FUNCTION fileobject. close() will be used to close the file object, once we have finished working on it. The method will free up all the system resources used by the file, this means that once file is closed, we will not be able to use the file object any more. For example: f.close()
  • 37. THANK YOU & HAVE A NICE DAY UNDER THE GUIDANCE OF KVS RO AGRA VEDIO LESSON PREPARED BY: KIRTI GUPTA PGT(CS) KV NTPC DADRI