SlideShare a Scribd company logo
FILE HANDLING
 INTRODUCTION
 DATA FILES
 OPENINGANDCLOSING FILES
 READINGANDWRITING FILES
 STANDARD INPUT,OUTPUTAND ERRORSTREAMS
Introduction
 FILE HANDLING is a mechanism by which we
can read data of disk files in python program or
write back data from python program to disk
files.
 So far in our python program the standard input
in coming from keyboard an output is going to
monitor i.e. no where data is stored permanent
and entered data is present as long as program is
running BUT file handling allows us to store data
entered through python program permanently in
disk file and later on we can read back the data
DATA FILES
 It contains data pertaining to a specific
application, for later use. The data files can be
stored in two ways –
 Text File
 Binary File
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
Binary files
 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
the same.
Steps in Data File Handling
1. OPENING FILE
 We should first open the file for read or write by
specifying the name of file and mode.
2. PERFORMING READ/WRITE
 Once the file is opened now we can either read or
write for which file is opened using various functions
available
3. CLOSING FILE
 After performing operation we must close the file
and release the file for other application to use it,
Opening File
 File can be opened for either – read, write,
append.
SYNTAX:
file_object = open(filename)
Or
file_object = open(filename,mode)
** default mode is “read”
Opening File
myfile = open(“story.txt”)
here disk file “story.txt” is loaded in
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.
Opening File
myfile = open(“article.txt”,”r”)
here “r” is for read (although it is by default, other
options are “w” for write, “a” for append)
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
Opening File
myfile = open(“d:mydatapoem.txt”,”r”)
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”)
File Handle
myfile = open(r“d:mydatapoem.txt”,”r”)
In the above example “myfile” is the file object
or file handle or file pointer holding the
reference of disk file. In python we will access
and manipulate the disk file through this file
handle only.
File Access Mode
Text
File
Mode
Binary File
Mode
Description Notes
‘r’ ‘rb’ Read only File must exists, otherwise Python raises
I/O errors
‘w’ ‘wb’ Write only If file not exists, file is created
If file exists, python will truncate
existing data and overwrite the file.
‘a’ ‘ab’ Append File is in write mode only, new data will
be added to the end of existing data i.e.
no overwriting. If file not exists it is
created
‘r+’ ‘r+b’ or ‘rb+’ Read and write File must exists otherwise error is raised
Both reading and writing can take place
w+ ‘w+b’ or ‘wb+’ Write and read File is created if not exists, if exists data
will be truncated, both read and write
allowed
‘a+’
VINOD K
SAC
‘a+b’ or ‘ab+’
UMARVERMA,PGT(CS),
HIN BHARDWAJ, PGT(CS)
Write and read
KV OEF KANPUR&
, KV NO.1TEZPUR
Same as above but previous content will
be retained and both read and write.
Closing file
 As reference of disk file is stored in file handle
so to close we must call the close() function
through the file handle and release the file.
myfile.close()
Note: open function is built-in function used
standalone while close() must be called through file
handle
Reading from File
 To read from file python provide many functions
like :
 Filehandle.read([n]) : reads and return n bytes,
if n is not specified it reads entire file.
 Filehandle.readline([n]) : reads a line of input.
If n is specified reads at most n bytes. Read bytes
in the form of string ending with line character or
blank string if no more bytes are left for reading.
 Filehandle.readlines(): reads all lines and
returns them in a list
Example-1: read()
SAMPLE FILE
Example-2: read()
SAMPLE FILE
Example-3: readline()
SAMPLE FILE
Writing onto files
 After read operation, let us take an example
of how to write data in disk files. Python
provides functions:
 write ()
 writelines()
 The above functions are called by the file
handle to write desired content.
Name Syntax Description
write() Filehandle.write(str1) Writes string str1 to file referenced
by filehandle
Writelines() Filehandle.writelines(L) Writes all string in List L as lines to
file referenced by filehandle.
Example-1: write() using “w” mode
Example-1: write() using “w” mode
Lets run the
same program
again
Example-1: write() using “w” mode
Now we can observe that while writing data to file using “w” mode the previous
content of existing file will be overwritten and new content will be saved.
If we want to add new data without overwriting the previous content then we
should write using “a” mode i.e. append mode.
Example-2: write() using “a” mode
New content is
added after previous
content
Example-3: using writelines()
Example-4: Writing String as a record
to file
Example-5: To copy the content of one
file to another file
Ad

More Related Content

Similar to FILE HANDLING in python to understand basic operations. (20)

Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
Koteswari Kasireddy
 
Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
Koteswari Kasireddy
 
Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
Praveen M Jigajinni
 
FILE HANDLING IN PYTHON Presentation Computer Science
FILE HANDLING IN PYTHON Presentation Computer ScienceFILE HANDLING IN PYTHON Presentation Computer Science
FILE HANDLING IN PYTHON Presentation Computer Science
HargunKaurGrover
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
vsol7206
 
file handling in python using exception statement
file handling in python using exception statementfile handling in python using exception statement
file handling in python using exception statement
srividhyaarajagopal
 
pspp-rsk.pptx
pspp-rsk.pptxpspp-rsk.pptx
pspp-rsk.pptx
ARYAN552812
 
Data file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing filesData file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing files
keeeerty
 
Data file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing filesData file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing files
Keerty Smile
 
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
 
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
CHAPTER 2 - FILE HANDLING-txtfile.pdf is hereCHAPTER 2 - FILE HANDLING-txtfile.pdf is here
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
sidbhat290907
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
Ashwini Raut
 
Python-FileHandling.pptx
Python-FileHandling.pptxPython-FileHandling.pptx
Python-FileHandling.pptx
Karudaiyar Ganapathy
 
FILE HANDLING COMPUTER SCIENCE -FILES.pptx
FILE HANDLING COMPUTER SCIENCE -FILES.pptxFILE HANDLING COMPUTER SCIENCE -FILES.pptx
FILE HANDLING COMPUTER SCIENCE -FILES.pptx
anushasabhapathy76
 
FILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxFILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptx
ssuserd0df33
 
for interview this ppt is a teching aid for file handling concepts includes t...
for interview this ppt is a teching aid for file handling concepts includes t...for interview this ppt is a teching aid for file handling concepts includes t...
for interview this ppt is a teching aid for file handling concepts includes t...
Primary2Primary2
 
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
 
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
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
Mehul Desai
 
File handling3.pdf
File handling3.pdfFile handling3.pdf
File handling3.pdf
nishant874609
 
FILE HANDLING IN PYTHON Presentation Computer Science
FILE HANDLING IN PYTHON Presentation Computer ScienceFILE HANDLING IN PYTHON Presentation Computer Science
FILE HANDLING IN PYTHON Presentation Computer Science
HargunKaurGrover
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
vsol7206
 
file handling in python using exception statement
file handling in python using exception statementfile handling in python using exception statement
file handling in python using exception statement
srividhyaarajagopal
 
Data file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing filesData file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing files
keeeerty
 
Data file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing filesData file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing files
Keerty Smile
 
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
 
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
CHAPTER 2 - FILE HANDLING-txtfile.pdf is hereCHAPTER 2 - FILE HANDLING-txtfile.pdf is here
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
sidbhat290907
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
Ashwini Raut
 
FILE HANDLING COMPUTER SCIENCE -FILES.pptx
FILE HANDLING COMPUTER SCIENCE -FILES.pptxFILE HANDLING COMPUTER SCIENCE -FILES.pptx
FILE HANDLING COMPUTER SCIENCE -FILES.pptx
anushasabhapathy76
 
FILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxFILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptx
ssuserd0df33
 
for interview this ppt is a teching aid for file handling concepts includes t...
for interview this ppt is a teching aid for file handling concepts includes t...for interview this ppt is a teching aid for file handling concepts includes t...
for interview this ppt is a teching aid for file handling concepts includes t...
Primary2Primary2
 
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
 
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
 

Recently uploaded (20)

seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjjseninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
AjijahamadKhaji
 
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
ajayrm685
 
hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .
NABLAS株式会社
 
Applications of Centroid in Structural Engineering
Applications of Centroid in Structural EngineeringApplications of Centroid in Structural Engineering
Applications of Centroid in Structural Engineering
suvrojyotihalder2006
 
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
AI Publications
 
Construction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil EngineeringConstruction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil Engineering
Lavish Kashyap
 
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdfDavid Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry
 
Agents chapter of Artificial intelligence
Agents chapter of Artificial intelligenceAgents chapter of Artificial intelligence
Agents chapter of Artificial intelligence
DebdeepMukherjee9
 
Water Industry Process Automation & Control Monthly May 2025
Water Industry Process Automation & Control Monthly May 2025Water Industry Process Automation & Control Monthly May 2025
Water Industry Process Automation & Control Monthly May 2025
Water Industry Process Automation & Control
 
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdfSmart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
PawachMetharattanara
 
Slide share PPT of NOx control technologies.pptx
Slide share PPT of  NOx control technologies.pptxSlide share PPT of  NOx control technologies.pptx
Slide share PPT of NOx control technologies.pptx
vvsasane
 
2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt
rakshaiya16
 
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
22PCOAM16 ML Unit 3 Full notes PDF & QB.pdf
Guru Nanak Technical Institutions
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
Working with USDOT UTCs: From Conception to Implementation
Working with USDOT UTCs: From Conception to ImplementationWorking with USDOT UTCs: From Conception to Implementation
Working with USDOT UTCs: From Conception to Implementation
Alabama Transportation Assistance Program
 
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdfML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
rameshwarchintamani
 
Generative AI & Large Language Models Agents
Generative AI & Large Language Models AgentsGenerative AI & Large Language Models Agents
Generative AI & Large Language Models Agents
aasgharbee22seecs
 
Frontend Architecture Diagram/Guide For Frontend Engineers
Frontend Architecture Diagram/Guide For Frontend EngineersFrontend Architecture Diagram/Guide For Frontend Engineers
Frontend Architecture Diagram/Guide For Frontend Engineers
Michael Hertzberg
 
Using the Artificial Neural Network to Predict the Axial Strength and Strain ...
Using the Artificial Neural Network to Predict the Axial Strength and Strain ...Using the Artificial Neural Network to Predict the Axial Strength and Strain ...
Using the Artificial Neural Network to Predict the Axial Strength and Strain ...
Journal of Soft Computing in Civil Engineering
 
Machine foundation notes for civil engineering students
Machine foundation notes for civil engineering studentsMachine foundation notes for civil engineering students
Machine foundation notes for civil engineering students
DYPCET
 
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjjseninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
AjijahamadKhaji
 
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
ajayrm685
 
hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .
NABLAS株式会社
 
Applications of Centroid in Structural Engineering
Applications of Centroid in Structural EngineeringApplications of Centroid in Structural Engineering
Applications of Centroid in Structural Engineering
suvrojyotihalder2006
 
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
Empowering Electric Vehicle Charging Infrastructure with Renewable Energy Int...
AI Publications
 
Construction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil EngineeringConstruction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil Engineering
Lavish Kashyap
 
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdfDavid Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry
 
Agents chapter of Artificial intelligence
Agents chapter of Artificial intelligenceAgents chapter of Artificial intelligence
Agents chapter of Artificial intelligence
DebdeepMukherjee9
 
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdfSmart City is the Future EN - 2024 Thailand Modify V1.0.pdf
Smart City is the Future EN - 2024 Thailand Modify V1.0.pdf
PawachMetharattanara
 
Slide share PPT of NOx control technologies.pptx
Slide share PPT of  NOx control technologies.pptxSlide share PPT of  NOx control technologies.pptx
Slide share PPT of NOx control technologies.pptx
vvsasane
 
2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt
rakshaiya16
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdfML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
rameshwarchintamani
 
Generative AI & Large Language Models Agents
Generative AI & Large Language Models AgentsGenerative AI & Large Language Models Agents
Generative AI & Large Language Models Agents
aasgharbee22seecs
 
Frontend Architecture Diagram/Guide For Frontend Engineers
Frontend Architecture Diagram/Guide For Frontend EngineersFrontend Architecture Diagram/Guide For Frontend Engineers
Frontend Architecture Diagram/Guide For Frontend Engineers
Michael Hertzberg
 
Machine foundation notes for civil engineering students
Machine foundation notes for civil engineering studentsMachine foundation notes for civil engineering students
Machine foundation notes for civil engineering students
DYPCET
 
Ad

FILE HANDLING in python to understand basic operations.

  • 1. FILE HANDLING  INTRODUCTION  DATA FILES  OPENINGANDCLOSING FILES  READINGANDWRITING FILES  STANDARD INPUT,OUTPUTAND ERRORSTREAMS
  • 2. Introduction  FILE HANDLING is a mechanism by which we can read data of disk files in python program or write back data from python program to disk files.  So far in our python program the standard input in coming from keyboard an output is going to monitor i.e. no where data is stored permanent and entered data is present as long as program is running BUT file handling allows us to store data entered through python program permanently in disk file and later on we can read back the data
  • 3. DATA FILES  It contains data pertaining to a specific application, for later use. The data files can be stored in two ways –  Text File  Binary File
  • 4. 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
  • 5. Binary files  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 the same.
  • 6. Steps in Data File Handling 1. OPENING FILE  We should first open the file for read or write by specifying the name of file and mode. 2. PERFORMING READ/WRITE  Once the file is opened now we can either read or write for which file is opened using various functions available 3. CLOSING FILE  After performing operation we must close the file and release the file for other application to use it,
  • 7. Opening File  File can be opened for either – read, write, append. SYNTAX: file_object = open(filename) Or file_object = open(filename,mode) ** default mode is “read”
  • 8. Opening File myfile = open(“story.txt”) here disk file “story.txt” is loaded in 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.
  • 9. Opening File myfile = open(“article.txt”,”r”) here “r” is for read (although it is by default, other options are “w” for write, “a” for append) 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
  • 10. Opening File myfile = open(“d:mydatapoem.txt”,”r”) 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”)
  • 11. File Handle myfile = open(r“d:mydatapoem.txt”,”r”) In the above example “myfile” is the file object or file handle or file pointer holding the reference of disk file. In python we will access and manipulate the disk file through this file handle only.
  • 12. File Access Mode Text File Mode Binary File Mode Description Notes ‘r’ ‘rb’ Read only File must exists, otherwise Python raises I/O errors ‘w’ ‘wb’ Write only If file not exists, file is created If file exists, python will truncate existing data and overwrite the file. ‘a’ ‘ab’ Append File is in write mode only, new data will be added to the end of existing data i.e. no overwriting. If file not exists it is created ‘r+’ ‘r+b’ or ‘rb+’ Read and write File must exists otherwise error is raised Both reading and writing can take place w+ ‘w+b’ or ‘wb+’ Write and read File is created if not exists, if exists data will be truncated, both read and write allowed ‘a+’ VINOD K SAC ‘a+b’ or ‘ab+’ UMARVERMA,PGT(CS), HIN BHARDWAJ, PGT(CS) Write and read KV OEF KANPUR& , KV NO.1TEZPUR Same as above but previous content will be retained and both read and write.
  • 13. Closing file  As reference of disk file is stored in file handle so to close we must call the close() function through the file handle and release the file. myfile.close() Note: open function is built-in function used standalone while close() must be called through file handle
  • 14. Reading from File  To read from file python provide many functions like :  Filehandle.read([n]) : reads and return n bytes, if n is not specified it reads entire file.  Filehandle.readline([n]) : reads a line of input. If n is specified reads at most n bytes. Read bytes in the form of string ending with line character or blank string if no more bytes are left for reading.  Filehandle.readlines(): reads all lines and returns them in a list
  • 18. Writing onto files  After read operation, let us take an example of how to write data in disk files. Python provides functions:  write ()  writelines()  The above functions are called by the file handle to write desired content. Name Syntax Description write() Filehandle.write(str1) Writes string str1 to file referenced by filehandle Writelines() Filehandle.writelines(L) Writes all string in List L as lines to file referenced by filehandle.
  • 19. Example-1: write() using “w” mode
  • 20. Example-1: write() using “w” mode Lets run the same program again
  • 21. Example-1: write() using “w” mode Now we can observe that while writing data to file using “w” mode the previous content of existing file will be overwritten and new content will be saved. If we want to add new data without overwriting the previous content then we should write using “a” mode i.e. append mode.
  • 22. Example-2: write() using “a” mode New content is added after previous content
  • 24. Example-4: Writing String as a record to file
  • 25. Example-5: To copy the content of one file to another file
  翻译: