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

More Related Content

What's hot (18)

File and directories in python
File and directories in pythonFile and directories in python
File and directories in python
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
File Handling In C++(OOPs))
File Handling In C++(OOPs))File Handling In C++(OOPs))
File Handling In C++(OOPs))
 
Filehadnling
FilehadnlingFilehadnling
Filehadnling
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
 
File Handling
File HandlingFile Handling
File Handling
 
Files in c++
Files in c++Files in c++
Files in c++
 
File Handling In C++
File Handling In C++File Handling In C++
File Handling In C++
 
File handling in C++
File handling in C++File handling in C++
File handling in C++
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
C files
C filesC files
C files
 
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUSFILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
 

Similar to 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 handling in c
File handling in cFile handling in c
File handling in caakanksha s
 
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
 
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
 

Similar to 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
 
Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
 
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
 
working with files
working with filesworking with files
working with files
 
File handling in c
File handling in cFile handling in c
File handling in c
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
 
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
 
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
 

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 introduction,opening &amp; closing files
Data file handling in python introduction,opening &amp; closing filesData file handling in python introduction,opening &amp; closing files
Data file handling in python introduction,opening &amp; closing filesKeerty 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 introduction,opening &amp; closing files
Data file handling in python introduction,opening &amp; closing filesData file handling in python introduction,opening &amp; closing files
Data file handling in python introduction,opening &amp; closing files
 
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

mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
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
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
_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
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
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
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
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
 

Recently uploaded (20)

mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.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
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
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
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
_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
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
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
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
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
 

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