SlideShare ist ein Scribd-Unternehmen logo
1 von 39
TEXT FILE READING & WRITING METHODS
FILE READING
PYTHON
PROGRA
M
A Program reads a text/binary file
from hard disk. File acts like an input to a
program.
FILE READING METHODS
Followings are the methods to read a data
from the file.
1. readline() METHOD
2. readlines() METHOD
3. read() METHOD
readline() METHOD
readline() will return a line read, as a string
from the file. First call to function will return
first line, second call next line and so on.
It's syntax is,
fileobject.readline()
readline() EXAMPLE
First create a text file and save under
filename notes.txt
readline() EXAMPLE
readline() EXAMPLE O/P
readline() will return only one line from a
file, but notes.txt file containing three lines
of text
readlines() METHOD
readlines()can be used to read the entire content of the file. You
need to be careful while using it w.r.t. size of memory required before
using the function. The method will return a list of strings, each
separated by n. An example of reading entire data of file in list is:
It's syntax is,
fileobject.readlines()
as it returns a list, which can then be used for manipulation.
readlines() EXAMPLE
readlines() EXAMPLE
The readlines() method will return a
list of strings, each separated by n
read() METHOD
The read() method is used to read
entire file
The syntax is:
fileobject.read()
For example
Contd…
read() METHOD EXAMPLE
read() METHOD EXAMPLE O/P
The read() method will return entire
file.
read(size) METHOD
read(size) METHOD
read() can be used to read specific
size string from file. This function also
returns a string read from the file.
Syntax of read() function is:
fileobject.read([size])
For Example:
f.read(1) will read single
byte or character from a file.
read(size) METHOD EXAMPLE
f.read(1) will read single byte or character
from a file and assigns to x.
read(size) METHOD EXAMPLE O/P
WRITING IN TO FILE
WRITING METHODS
PYTHON
PROGRA
M
A Program writes into a text/binary file from
hard disk.
WRITING METHODS
1. write () METHOD
2. writelines() METHOD
1. write () METHOD
For sending data in file, i.e. to create /
write in the file, write() and writelines()
methods can be used.
write() method takes a string ( as
parameter ) and writes it in the file.
For storing data with end of line
character, you will have to add n character
to end of the string
write() using “w” mode
write() using “w” mode
Lets run the
same program
again
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.
write() USING “a” MODE
New content is
added after
previous content
2. writelines() METHOD
For writing a string at a time, we use write()
method, it can't be used for writing a list, tuple etc.
into a file.
Sequence data type can be written using
writelines() method in the file. It's not that, we can't
write a string using writelines() method.
It's syntax is:
fileobject.writelines(seq)
2. writelines() METHOD
So, whenever we have to write a
sequence of string / data type, we will use
writelines(), instead of write().
Example:
f = open('test2.txt','w')
str = 'hello world.n this is my first file
handling program.n I am using python
language"
f.writelines(str)
f.close()
Example Programs
Writing String as a record to file
Example :To copy the content of one file to
another file
Removing
from file
whitespaces after reading
 read() and readline() reads data from file and
return it in the form of string and readlines()
returns data in the form of list.
 All these read function also read leading and
trailing whitespaces, new line characters. If
you want to remove these characters you can
use functions
 strip() : removes the given character from both
ends.
 lstrip(): removes given character from left end
 rstrip(): removes given character from right end
Example: strip(),lstrip(),
rstrip()
File Pointer
 Every file maintains a file pointer which tells
the current position in the file where reading
and writing operation will take.
 When we perform any read/write operation
two things happens:
 The operation at the current position of file pointer
 File pointer advances by the specified number of
bytes.
Example
myfile = open(“ipl.txt”,”r”)
File pointer will be by default at first position i.e. first character
ch = myfile.read(1)
ch will store first character i.e. first character is consumed, and file pointer will
move to next character
File Modes and Opening position
of file pointer
FILE MODE OPENING POSITION
r, r+, rb, rb+, r+b Beginning of file
w, w+, wb, wb+, w+b Beginning of file (overwrites the file if
file already exists
a, ab, a+, ab+, a+b At the end of file if file exists otherwise
creates a new file
Set File offset in Python
Tell() Method
This method gives you the current offset of the file pointer in a file.
Syntax:
file.tell()
The tell() method doesn’t require any argument.
Seek() Method
This method can help you change the position of a file pointer in a file.
Syntax:
file.seek(offset[, from])
The <offset> argument represents the size of the displacement.
file.seek(offset[, from])
The <from> argument indicates the start point.
If from is 0, then the shift will start from the root level.
If from is 1, then the reference position will become the current position.
It from is 2, then the end of the file would serve as the reference position.
Example: Setting offsets in Python
with open('app.log', 'w', encoding = 'utf-8') as f:
#first line
f.write('It is my first filen')
#second line
f.write('This filen')
#third line
f.write('contains three linesn')
#Open a file
f = open('app.log', 'r+')
data = f.read(19);
print('Read String is : ', data)
#Check current position
position = f.tell();
print('Current file position : ', position)
#Reposition pointer at the beginning once again
position = f.seek(0, 0);
data = f.read(19);
print('Again read String is : ', data)
#Close the opened file
f.close() Read String is : It is my first file
Current file position : 19
Again read String is : It is my first file
OUTPUT
It is my first file
This file
contains three lines
App.log
Standard INPUT, OUTPUT and ERROR STREAM
Most programs make output to "standard out“,input from "standard in“, and error
messages go to standard error).standard output is to monitor and standard input is
from keyboard.
e.g.program
import sys
a = sys.stdin.readline()
sys.stdout.write(a)
a = sys.stdin.read(5)#entered 10 characters.a contains 5 characters.
#The remaining characters are waiting to be read. sys.stdout.write(a)
b = sys.stdin.read(5)
sys.stdout.write(b)
sys.stderr.write("ncustom error message")
THANK YOU &
HAVE A NICE DAY
UNDER THE GUIDANCE OF KVS RO AGRA
VEDIO LESSON PREPARED BY:
KIRTI GUPTA
PGT(CS)
KV NTPC DADRI

Weitere ähnliche Inhalte

Was ist angesagt? (20)

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
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
 
File Handling in Python
File Handling in PythonFile Handling in Python
File Handling in Python
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
 
Strings in python
Strings in pythonStrings in python
Strings in python
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Variables in python
Variables in pythonVariables in python
Variables in python
 
Java file
Java fileJava file
Java file
 
File handling in C++
File handling in C++File handling in C++
File handling in C++
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
Python functions
Python functionsPython functions
Python functions
 
NUMPY
NUMPY NUMPY
NUMPY
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Python Modules
Python ModulesPython Modules
Python Modules
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in python
 
File Handling In C++
File Handling In C++File Handling In C++
File Handling In C++
 
Csv file read and write
Csv file read and writeCsv file read and write
Csv file read and write
 

Ähnlich wie Data file handling in python reading & writing methods

DFH PDF-converted.pptx
DFH PDF-converted.pptxDFH PDF-converted.pptx
DFH PDF-converted.pptxAmitKaur17
 
FILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxFILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxssuserd0df33
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugevsol7206
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfsangeeta borde
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++Vineeta Garg
 
File Handling Topic for tech management you know na tho kyuon puch raha hai sale
File Handling Topic for tech management you know na tho kyuon puch raha hai saleFile Handling Topic for tech management you know na tho kyuon puch raha hai sale
File Handling Topic for tech management you know na tho kyuon puch raha hai saleRohitKurdiya1
 
Chapter28 data-file-handling
Chapter28 data-file-handlingChapter28 data-file-handling
Chapter28 data-file-handlingDeepak Singh
 
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 management in C++
File management in C++File management in C++
File management in C++apoorvaverma33
 

Ähnlich wie Data file handling in python reading & writing methods (20)

FILE HANDLING.pptx
FILE HANDLING.pptxFILE HANDLING.pptx
FILE HANDLING.pptx
 
DFH PDF-converted.pptx
DFH PDF-converted.pptxDFH PDF-converted.pptx
DFH PDF-converted.pptx
 
File Handling in C++
File Handling in C++File Handling in C++
File Handling in C++
 
FILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxFILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptx
 
Data file handling
Data file handlingData file handling
Data file handling
 
File Handling
File HandlingFile Handling
File Handling
 
working with files
working with filesworking with files
working with files
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
 
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
File Handling Topic for tech management you know na tho kyuon puch raha hai sale
File Handling Topic for tech management you know na tho kyuon puch raha hai saleFile Handling Topic for tech management you know na tho kyuon puch raha hai sale
File Handling Topic for tech management you know na tho kyuon puch raha hai sale
 
Chapter28 data-file-handling
Chapter28 data-file-handlingChapter28 data-file-handling
Chapter28 data-file-handling
 
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.
 
Module2-Files.pdf
Module2-Files.pdfModule2-Files.pdf
Module2-Files.pdf
 
PPS-II UNIT-5 PPT.pptx
PPS-II  UNIT-5 PPT.pptxPPS-II  UNIT-5 PPT.pptx
PPS-II UNIT-5 PPT.pptx
 
Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9
 
file handling.pdf
file handling.pdffile handling.pdf
file handling.pdf
 
File management in C++
File management in C++File management in C++
File management in C++
 
Unit V.pptx
Unit V.pptxUnit V.pptx
Unit V.pptx
 

Kürzlich hochgeladen

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 

Kürzlich hochgeladen (20)

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
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🔝
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 

Data file handling in python reading & writing methods

  • 1. TEXT FILE READING & WRITING METHODS
  • 2. FILE READING PYTHON PROGRA M A Program reads a text/binary file from hard disk. File acts like an input to a program.
  • 3. FILE READING METHODS Followings are the methods to read a data from the file. 1. readline() METHOD 2. readlines() METHOD 3. read() METHOD
  • 4. readline() METHOD readline() will return a line read, as a string from the file. First call to function will return first line, second call next line and so on. It's syntax is, fileobject.readline()
  • 5. readline() EXAMPLE First create a text file and save under filename notes.txt
  • 7. readline() EXAMPLE O/P readline() will return only one line from a file, but notes.txt file containing three lines of text
  • 8. readlines() METHOD readlines()can be used to read the entire content of the file. You need to be careful while using it w.r.t. size of memory required before using the function. The method will return a list of strings, each separated by n. An example of reading entire data of file in list is: It's syntax is, fileobject.readlines() as it returns a list, which can then be used for manipulation.
  • 10. readlines() EXAMPLE The readlines() method will return a list of strings, each separated by n
  • 11. read() METHOD The read() method is used to read entire file The syntax is: fileobject.read() For example Contd…
  • 13. read() METHOD EXAMPLE O/P The read() method will return entire file.
  • 15. read(size) METHOD read() can be used to read specific size string from file. This function also returns a string read from the file. Syntax of read() function is: fileobject.read([size]) For Example: f.read(1) will read single byte or character from a file.
  • 16. read(size) METHOD EXAMPLE f.read(1) will read single byte or character from a file and assigns to x.
  • 19. WRITING METHODS PYTHON PROGRA M A Program writes into a text/binary file from hard disk.
  • 20. WRITING METHODS 1. write () METHOD 2. writelines() METHOD
  • 21. 1. write () METHOD For sending data in file, i.e. to create / write in the file, write() and writelines() methods can be used. write() method takes a string ( as parameter ) and writes it in the file. For storing data with end of line character, you will have to add n character to end of the string
  • 23. write() using “w” mode Lets run the same program again
  • 24. 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.
  • 25. write() USING “a” MODE New content is added after previous content
  • 26. 2. writelines() METHOD For writing a string at a time, we use write() method, it can't be used for writing a list, tuple etc. into a file. Sequence data type can be written using writelines() method in the file. It's not that, we can't write a string using writelines() method. It's syntax is: fileobject.writelines(seq)
  • 27. 2. writelines() METHOD So, whenever we have to write a sequence of string / data type, we will use writelines(), instead of write(). Example: f = open('test2.txt','w') str = 'hello world.n this is my first file handling program.n I am using python language" f.writelines(str) f.close()
  • 28. Example Programs Writing String as a record to file
  • 29. Example :To copy the content of one file to another file
  • 30. Removing from file whitespaces after reading  read() and readline() reads data from file and return it in the form of string and readlines() returns data in the form of list.  All these read function also read leading and trailing whitespaces, new line characters. If you want to remove these characters you can use functions  strip() : removes the given character from both ends.  lstrip(): removes given character from left end  rstrip(): removes given character from right end
  • 32. File Pointer  Every file maintains a file pointer which tells the current position in the file where reading and writing operation will take.  When we perform any read/write operation two things happens:  The operation at the current position of file pointer  File pointer advances by the specified number of bytes.
  • 33. Example myfile = open(“ipl.txt”,”r”) File pointer will be by default at first position i.e. first character ch = myfile.read(1) ch will store first character i.e. first character is consumed, and file pointer will move to next character
  • 34. File Modes and Opening position of file pointer FILE MODE OPENING POSITION r, r+, rb, rb+, r+b Beginning of file w, w+, wb, wb+, w+b Beginning of file (overwrites the file if file already exists a, ab, a+, ab+, a+b At the end of file if file exists otherwise creates a new file
  • 35. Set File offset in Python Tell() Method This method gives you the current offset of the file pointer in a file. Syntax: file.tell() The tell() method doesn’t require any argument. Seek() Method This method can help you change the position of a file pointer in a file. Syntax: file.seek(offset[, from]) The <offset> argument represents the size of the displacement.
  • 36. file.seek(offset[, from]) The <from> argument indicates the start point. If from is 0, then the shift will start from the root level. If from is 1, then the reference position will become the current position. It from is 2, then the end of the file would serve as the reference position. Example: Setting offsets in Python with open('app.log', 'w', encoding = 'utf-8') as f: #first line f.write('It is my first filen') #second line f.write('This filen') #third line f.write('contains three linesn')
  • 37. #Open a file f = open('app.log', 'r+') data = f.read(19); print('Read String is : ', data) #Check current position position = f.tell(); print('Current file position : ', position) #Reposition pointer at the beginning once again position = f.seek(0, 0); data = f.read(19); print('Again read String is : ', data) #Close the opened file f.close() Read String is : It is my first file Current file position : 19 Again read String is : It is my first file OUTPUT It is my first file This file contains three lines App.log
  • 38. Standard INPUT, OUTPUT and ERROR STREAM Most programs make output to "standard out“,input from "standard in“, and error messages go to standard error).standard output is to monitor and standard input is from keyboard. e.g.program import sys a = sys.stdin.readline() sys.stdout.write(a) a = sys.stdin.read(5)#entered 10 characters.a contains 5 characters. #The remaining characters are waiting to be read. sys.stdout.write(a) b = sys.stdin.read(5) sys.stdout.write(b) sys.stderr.write("ncustom error message")
  • 39. THANK YOU & HAVE A NICE DAY UNDER THE GUIDANCE OF KVS RO AGRA VEDIO LESSON PREPARED BY: KIRTI GUPTA PGT(CS) KV NTPC DADRI