SlideShare a Scribd company logo
1 of 6
Data File Handling
A file is a bunch of bytes stored on some storage device like hard disk, pen drive etc.
Files help in storing information permanently, they store data pertaining to a specific application.
These data files can be strored in two ways:
Text Files Binary Files
it stores information in ASCII or UNICODE characters.
Each line of text is terminated with special character known
as EOL(‘n’)
It contains information in the same format in which the
information is held in memory. (hexadecimal for us )
EOL is (‘rn’)
Internal translation take place when EOL character is read
or written. so text files are slower for programs to read and
write
No Internal translation take place when EOL character is
read or written. so binary files are faster and easier for
program to read and write.
it is most suitable when file need to be read by people. it is most suitable when file dont’ need to be read by people.
Standard Streams / Standard Devices - ( standard devices are implemented as standard streams)
1. stdin -> Standard input device -> keyboard -> reads from keyboard
2. stdout -> Standard Output device -> monitor-> writes to monitor
3. stderr -> Standard error device -> monitor -> writes only errors to monitor.
In python import sys module let us access these standard devices.
so instead of print(“hello world”) we can use sys.stdout.write(“hello world”)
Opening and closing File-
To work with a file within a program you need to open it.
While opening a file you need to mention appropriate
mode (r/w/a)
Function
/
Method
syntax- Example-
open()
(is a
function
)
fileobject=open(filename)
fileobject=open(filename,
mode)
‘’’establishes link between
fileobject/filehandle and a file on
disk.’’’
fi=open(“Input.txt”) OR fi=open(“..Input.txt”) OR fi=open(“d:programsInput.txt”)
fo=open(“Output.txt”,”w”) OR fo=open(“..Output.txt”,”w”) OR
fo=open(“d:programsOutput.txt”,”w”)
file object path to file mode
with open (filename,mode) as fileobject: with open (“Input.txt”,”r”) as fi: with open (“Output.txt”,”a”)
as fo:
file manipulation statement print(f.read(1)) fo.write(“Reaches to
end”)
close()
(is a
method
fileobject.close()
‘’’ breaks the link of fieobject and
file on disk.’’’
fi.close()
fo.close()
File modes
Text
File
Mode
Binary
File
Mode
Descripti
on
r w a Create a file
if does not
exist
Position of file pointer
on file opening
‘r’ ‘rb’ only read ✔ ✖ ✖ beginning of file
‘w’ ‘wb’ only write ✖ ✔ erases/truncates contents of the file
and start writing from beginning
(Overwrites the file)
✔ beginning of file
‘a’ ‘ab’ append
(only write)
✖ ✔ write only at end of the contents of the
existing file(retains old contents)
✔ if file doesn’t exist-
beginning of file
if file exists- end of the file
‘r+’ ‘r+b’ /
‘rb+’
read &
write
✔ ✔ ✖ beginning of file
‘w+’ ‘w+b’ /
‘wb+’
read &
write
✔ ✔ erases/ truncates contents of the file
and start writing from
beginning(Overwrites the file)
✔ beginning of file
‘a+’ ‘a+b’ /
‘ab+’
read &
write
✔ ✔ write only at end of the contents of the
existing file(retains old contents)
✔ if file doesn’t exist-
beginning of file
if file exists- end of the file
(Sequentially)Reading Writing Files
Method syntax Description example output
read() fileobject.read([n]) if n is specified reads ‘n’ bytes from
file otherwise reads entire file
returns read bytes in the form of
string
1) file=open('......story.txt','r')
l=file.read()
print(l)
print(type(l))
1) file=open('......story.txt','r')
l=file.read(6)
print(l)
print(type(l))
Jingle Bell Jingle bell
Jingle all the way
Oh! what fun it is to ride on
one horse open sledge.
<class 'str'>
Jingle
<class 'str'>
readline() fileobject.readline([n])
if n is specified reads n bytes from
file,otherwise reads a line of file from
current position,
returns read bytes in form of string
1) file=open('......story.txt','r')
l=file.readline() # add strip()
print(l)
print(type(l))
1) file=open('......story.txt','r')
l=file.readline(6)
print(l)
print(type(l))
Jingle Bell Jingle bell
<class 'str'>
Jingle
<class 'str'>
readlines(
)
fileobject.readlines()
reads all lines and returns them in a
form of list
1) file=open('......story.txt','r')
l=file.readlines()
print(l)
print(type(l))
['Jingle Bell Jingle belln',
'Jingle all the wayn', 'Oh!
what fun it is to ride onn',
'one horse open sledge.']
Randomly reading writing files
Method syntax description example Output
tell() fileobject.tell() returns an integer giving the current
position of object in the file. The integer
returned specifies the number of bytes
from the beginning of the file till the
current position of file object.
f=open('story.txt','r+')
print(“position:”,f.tell()
)
fdata = f.read(7)
print (fdata)
print(“position:”,f.tell()
)
f.close()
0
Jingle
8
seek() fileobject.seek(offset [, from_what])
here
offset is reference point from_where
to get the position.
return position the file object at
particular place in the file.
list of from_where values:
Value reference point
0 beginning of the file
1 current position of file
2 end of file
*default value of from_where is 0, i.e.
beginning of the file
f=open('story.txt','r+')
f.seek(7)
fdata = f.read(7)
print fdata
f.close()
Let's read the second
word from the test1 file
created earlier. First
word is 5 alphabets, so
we need to move to 5th
byte. Offset of first byte
starts from zero.
Bell
We know that the methods provided in python for writing / reading a file works with string parameters.
So when we want to work on binary file, conversion of data at the time of reading, as well as writing is
required.
Pickle module can be used to store any kind of object in file as it allows us to store python objects with their
structure.
So for storing data in binary format, we will use pickle module.
First we need to import the module.
It provides two main methods for the purpose, dump and load.
Pickle Method Description Syntax Example:
dump() - to write the object in file, which
is opened in binary access
mode.
pickle.dump
(object, fileobject)
import pickle
l = [1,2,3,4,5,6]
file = open('list.dat', 'wb')
pickle.dump(l,file)
load() use pickle.load() to read the
object from file which is opened
in binary access mode.
object =
load(fileobject)
ifile = open('myfile.dat', 'rb')
L = pickle.load(ifile)
ifile.close()
print (L)

More Related Content

What's hot

File and directories in python
File and directories in pythonFile and directories in python
File and directories in pythonLifna C.S
 
File handling(some slides only)
File handling(some slides only)File handling(some slides only)
File handling(some slides only)Kamlesh Nishad
 
Php file handling in Hindi
Php file handling in Hindi Php file handling in Hindi
Php file handling in Hindi Vipin sharma
 
Files and Directories in PHP
Files and Directories in PHPFiles and Directories in PHP
Files and Directories in PHPNicole Ryan
 
Data file operations in C++ Base
Data file operations in C++ BaseData file operations in C++ Base
Data file operations in C++ BasearJun_M
 
Filing system in PHP
Filing system in PHPFiling system in PHP
Filing system in PHPMudasir Syed
 
Mesics lecture files in 'c'
Mesics lecture   files in 'c'Mesics lecture   files in 'c'
Mesics lecture files in 'c'eShikshak
 
File handling in c
File handling in c File handling in c
File handling in c Vikash Dhal
 
File Management in C
File Management in CFile Management in C
File Management in CPaurav Shah
 
File handling in C
File handling in CFile handling in C
File handling in CRabin BK
 
File handling in C by Faixan
File handling in C by FaixanFile handling in C by Faixan
File handling in C by FaixanٖFaiXy :)
 
Data file handling in python reading & writing methods
Data file handling in python reading & writing methodsData file handling in python reading & writing methods
Data file handling in python reading & writing methodskeeeerty
 

What's hot (20)

php file uploading
php file uploadingphp file uploading
php file uploading
 
Php File Operations
Php File OperationsPhp File Operations
Php File Operations
 
File in c
File in cFile in c
File in c
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in python
 
PHP file handling
PHP file handling PHP file handling
PHP file handling
 
Php files
Php filesPhp files
Php files
 
File handling(some slides only)
File handling(some slides only)File handling(some slides only)
File handling(some slides only)
 
File handling-c
File handling-cFile handling-c
File handling-c
 
Php file handling in Hindi
Php file handling in Hindi Php file handling in Hindi
Php file handling in Hindi
 
Files and Directories in PHP
Files and Directories in PHPFiles and Directories in PHP
Files and Directories in PHP
 
File in C Programming
File in C ProgrammingFile in C Programming
File in C Programming
 
Data file operations in C++ Base
Data file operations in C++ BaseData file operations in C++ Base
Data file operations in C++ Base
 
C files
C filesC files
C files
 
Filing system in PHP
Filing system in PHPFiling system in PHP
Filing system in PHP
 
Mesics lecture files in 'c'
Mesics lecture   files in 'c'Mesics lecture   files in 'c'
Mesics lecture files in 'c'
 
File handling in c
File handling in c File handling in c
File handling in c
 
File Management in C
File Management in CFile Management in C
File Management in C
 
File handling in C
File handling in CFile handling in C
File handling in C
 
File handling in C by Faixan
File handling in C by FaixanFile handling in C by Faixan
File handling in C by Faixan
 
Data file handling in python reading & writing methods
Data file handling in python reading & writing methodsData file handling in python reading & writing methods
Data file handling in python reading & writing methods
 

Similar to Python data file handling

Similar to Python data file handling (20)

FILE HANDLING.pptx
FILE HANDLING.pptxFILE HANDLING.pptx
FILE HANDLING.pptx
 
presentation_files_1451938150_140676.ppt
presentation_files_1451938150_140676.pptpresentation_files_1451938150_140676.ppt
presentation_files_1451938150_140676.ppt
 
files in c ppt.ppt
files in c ppt.pptfiles in c ppt.ppt
files in c ppt.ppt
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
 
PPS PPT 2.pptx
PPS PPT 2.pptxPPS PPT 2.pptx
PPS PPT 2.pptx
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
 
File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).ppt
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
PPS-II UNIT-5 PPT.pptx
PPS-II  UNIT-5 PPT.pptxPPS-II  UNIT-5 PPT.pptx
PPS-II UNIT-5 PPT.pptx
 
File Handling in python.docx
File Handling in python.docxFile Handling in python.docx
File Handling in python.docx
 
files.pptx
files.pptxfiles.pptx
files.pptx
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
 
pspp-rsk.pptx
pspp-rsk.pptxpspp-rsk.pptx
pspp-rsk.pptx
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
Files in c++
Files in c++Files in c++
Files in c++
 
Python file handlings
Python file handlingsPython file handlings
Python file handlings
 
FILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxFILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptx
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
 
Module2-Files.pdf
Module2-Files.pdfModule2-Files.pdf
Module2-Files.pdf
 
Module 5 file cp
Module 5 file cpModule 5 file cp
Module 5 file cp
 

More from ToniyaP1

Data structures: linear lists
Data structures: linear listsData structures: linear lists
Data structures: linear listsToniyaP1
 
Python library
Python libraryPython library
Python libraryToniyaP1
 
Python algorithm efficency
Python algorithm efficencyPython algorithm efficency
Python algorithm efficencyToniyaP1
 
Python functions
Python functionsPython functions
Python functionsToniyaP1
 
Python recursion
Python recursionPython recursion
Python recursionToniyaP1
 

More from ToniyaP1 (6)

Numpy
NumpyNumpy
Numpy
 
Data structures: linear lists
Data structures: linear listsData structures: linear lists
Data structures: linear lists
 
Python library
Python libraryPython library
Python library
 
Python algorithm efficency
Python algorithm efficencyPython algorithm efficency
Python algorithm efficency
 
Python functions
Python functionsPython functions
Python functions
 
Python recursion
Python recursionPython recursion
Python recursion
 

Recently uploaded

DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
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
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
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
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
“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
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
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
 
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
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
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
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
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
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 

Recently uploaded (20)

DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
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
 
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🔝
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
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
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
“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...
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
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
 
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
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
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
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
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
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 

Python data file handling

  • 1. Data File Handling A file is a bunch of bytes stored on some storage device like hard disk, pen drive etc. Files help in storing information permanently, they store data pertaining to a specific application. These data files can be strored in two ways: Text Files Binary Files it stores information in ASCII or UNICODE characters. Each line of text is terminated with special character known as EOL(‘n’) It contains information in the same format in which the information is held in memory. (hexadecimal for us ) EOL is (‘rn’) Internal translation take place when EOL character is read or written. so text files are slower for programs to read and write No Internal translation take place when EOL character is read or written. so binary files are faster and easier for program to read and write. it is most suitable when file need to be read by people. it is most suitable when file dont’ need to be read by people. Standard Streams / Standard Devices - ( standard devices are implemented as standard streams) 1. stdin -> Standard input device -> keyboard -> reads from keyboard 2. stdout -> Standard Output device -> monitor-> writes to monitor 3. stderr -> Standard error device -> monitor -> writes only errors to monitor. In python import sys module let us access these standard devices. so instead of print(“hello world”) we can use sys.stdout.write(“hello world”)
  • 2. Opening and closing File- To work with a file within a program you need to open it. While opening a file you need to mention appropriate mode (r/w/a) Function / Method syntax- Example- open() (is a function ) fileobject=open(filename) fileobject=open(filename, mode) ‘’’establishes link between fileobject/filehandle and a file on disk.’’’ fi=open(“Input.txt”) OR fi=open(“..Input.txt”) OR fi=open(“d:programsInput.txt”) fo=open(“Output.txt”,”w”) OR fo=open(“..Output.txt”,”w”) OR fo=open(“d:programsOutput.txt”,”w”) file object path to file mode with open (filename,mode) as fileobject: with open (“Input.txt”,”r”) as fi: with open (“Output.txt”,”a”) as fo: file manipulation statement print(f.read(1)) fo.write(“Reaches to end”) close() (is a method fileobject.close() ‘’’ breaks the link of fieobject and file on disk.’’’ fi.close() fo.close()
  • 3. File modes Text File Mode Binary File Mode Descripti on r w a Create a file if does not exist Position of file pointer on file opening ‘r’ ‘rb’ only read ✔ ✖ ✖ beginning of file ‘w’ ‘wb’ only write ✖ ✔ erases/truncates contents of the file and start writing from beginning (Overwrites the file) ✔ beginning of file ‘a’ ‘ab’ append (only write) ✖ ✔ write only at end of the contents of the existing file(retains old contents) ✔ if file doesn’t exist- beginning of file if file exists- end of the file ‘r+’ ‘r+b’ / ‘rb+’ read & write ✔ ✔ ✖ beginning of file ‘w+’ ‘w+b’ / ‘wb+’ read & write ✔ ✔ erases/ truncates contents of the file and start writing from beginning(Overwrites the file) ✔ beginning of file ‘a+’ ‘a+b’ / ‘ab+’ read & write ✔ ✔ write only at end of the contents of the existing file(retains old contents) ✔ if file doesn’t exist- beginning of file if file exists- end of the file
  • 4. (Sequentially)Reading Writing Files Method syntax Description example output read() fileobject.read([n]) if n is specified reads ‘n’ bytes from file otherwise reads entire file returns read bytes in the form of string 1) file=open('......story.txt','r') l=file.read() print(l) print(type(l)) 1) file=open('......story.txt','r') l=file.read(6) print(l) print(type(l)) Jingle Bell Jingle bell Jingle all the way Oh! what fun it is to ride on one horse open sledge. <class 'str'> Jingle <class 'str'> readline() fileobject.readline([n]) if n is specified reads n bytes from file,otherwise reads a line of file from current position, returns read bytes in form of string 1) file=open('......story.txt','r') l=file.readline() # add strip() print(l) print(type(l)) 1) file=open('......story.txt','r') l=file.readline(6) print(l) print(type(l)) Jingle Bell Jingle bell <class 'str'> Jingle <class 'str'> readlines( ) fileobject.readlines() reads all lines and returns them in a form of list 1) file=open('......story.txt','r') l=file.readlines() print(l) print(type(l)) ['Jingle Bell Jingle belln', 'Jingle all the wayn', 'Oh! what fun it is to ride onn', 'one horse open sledge.']
  • 5. Randomly reading writing files Method syntax description example Output tell() fileobject.tell() returns an integer giving the current position of object in the file. The integer returned specifies the number of bytes from the beginning of the file till the current position of file object. f=open('story.txt','r+') print(“position:”,f.tell() ) fdata = f.read(7) print (fdata) print(“position:”,f.tell() ) f.close() 0 Jingle 8 seek() fileobject.seek(offset [, from_what]) here offset is reference point from_where to get the position. return position the file object at particular place in the file. list of from_where values: Value reference point 0 beginning of the file 1 current position of file 2 end of file *default value of from_where is 0, i.e. beginning of the file f=open('story.txt','r+') f.seek(7) fdata = f.read(7) print fdata f.close() Let's read the second word from the test1 file created earlier. First word is 5 alphabets, so we need to move to 5th byte. Offset of first byte starts from zero. Bell
  • 6. We know that the methods provided in python for writing / reading a file works with string parameters. So when we want to work on binary file, conversion of data at the time of reading, as well as writing is required. Pickle module can be used to store any kind of object in file as it allows us to store python objects with their structure. So for storing data in binary format, we will use pickle module. First we need to import the module. It provides two main methods for the purpose, dump and load. Pickle Method Description Syntax Example: dump() - to write the object in file, which is opened in binary access mode. pickle.dump (object, fileobject) import pickle l = [1,2,3,4,5,6] file = open('list.dat', 'wb') pickle.dump(l,file) load() use pickle.load() to read the object from file which is opened in binary access mode. object = load(fileobject) ifile = open('myfile.dat', 'rb') L = pickle.load(ifile) ifile.close() print (L)