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

File handling in Python
File handling in PythonFile handling in Python
File handling in PythonMegha V
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in pythonLifna C.S
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in pythonSantosh Verma
 
Python reading and writing files
Python reading and writing filesPython reading and writing files
Python reading and writing filesMukesh Tekwani
 
Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in pythonjunnubabu
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in PythonDevashish Kumar
 
Python- Regular expression
Python- Regular expressionPython- Regular expression
Python- Regular expressionMegha V
 
CBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary file
CBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary fileCBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary file
CBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary fileShivaniJayaprakash1
 
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...Edureka!
 
Date and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaDate and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaEdureka!
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++Vineeta Garg
 
Types of Statements in Python Programming Language
Types of Statements in Python Programming LanguageTypes of Statements in Python Programming Language
Types of Statements in Python Programming LanguageExplore Skilled
 
Function arguments In Python
Function arguments In PythonFunction arguments In Python
Function arguments In PythonAmit Upadhyay
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in pythonTMARAGATHAM
 
python Function
python Function python Function
python Function Ronak Rathi
 
File handling in C++
File handling in C++File handling in C++
File handling in C++Hitesh Kumar
 

What's hot (20)

File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in python
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
 
Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
 
Python reading and writing files
Python reading and writing filesPython reading and writing files
Python reading and writing files
 
Error and exception in python
Error and exception in pythonError and exception in python
Error and exception in python
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
Python- Regular expression
Python- Regular expressionPython- Regular expression
Python- Regular expression
 
CBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary file
CBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary fileCBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary file
CBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary file
 
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
 
Date and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaDate and Time Module in Python | Edureka
Date and Time Module in Python | Edureka
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
 
Types of Statements in Python Programming Language
Types of Statements in Python Programming LanguageTypes of Statements in Python Programming Language
Types of Statements in Python Programming Language
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
 
Function arguments In Python
Function arguments In PythonFunction arguments In Python
Function arguments In Python
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 
python Function
python Function python Function
python Function
 
File handling in C++
File handling in C++File handling in C++
File handling in C++
 
Python multithreaded programming
Python   multithreaded programmingPython   multithreaded programming
Python multithreaded programming
 

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
 
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 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
 
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
 

Recently uploaded

HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
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
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxLigayaBacuel1
 
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
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........LeaCamillePacle
 

Recently uploaded (20)

HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
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
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptx
 
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
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
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🔝
 
Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........
 

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