Lec 3 Coding File Handling
Files Container for storing data
Files are use to store data in
permanently
the memory of computer
Files arepermanently stored in the memory of
a computed and is stored in RAM while using i
E9 Fridge container to store food
Step 1 open the fridge
Nist
organise Adding
sep 2
Removing Replacing items
Step 3 close the door
Files container to store data
step 1 open the file
step 2 operations in file read write
step 3 Close the file append
Opening a file
Before performing operation in the file we must
any
open it first open method
using
Syntax open name of file mode
Assumption file and python code is present in the
same directory
Modes for file operations
read w read only mode
This mode opens the file for reading
This gives an error if file doesn't exist
This is also the default mode in while
file opens if no mode is mentioned in open
Eg f open myfile txt 97
same
08 8 Open [Link]
2 write w This mode opens the file for
writing on
Also This creates a new file if file doesnot
already exist
It overwrites the content in the file if
there is any
appentica mita én's
p site for appending
adding data at the end of prev data of
file
This creates a new file if it doesnot
already exist
Ex 8 open myfile txt a
Text files and
Binary files
Text files It stores information in the form of
stream of ASCII characters
As CSV comma separated values
TSV Tab separated values
Binary Files at stores data in form of stream of
bytes
It is not human readable
Info of binary files is used by
applications to display file in proper
format Eg pdf mp3 png
Modes for opening file
O r or ot read only Text file mode
rb Binary file mode
w or not write only Text file mode
Wb is a
Binary is it
a or at append Text file mode
ab append Binary file Mode
1
8 read and write mode for text
r b or obtt it is is it a
binary
File must exist otherwise error
W write and read mode for tex
11
Wtb or Wbt i i 11 11 binary
of file does not exist already it creates
a new file
at append and head mode for text
atb or abt for binary
If file doesnt exist already it
creates a new file
Operations working with Text files
Reading from Text files read
headline 7
headlines
head Syntax fileobject head n
no of characters of file
headlines syntax fileobject readline
It is use to read single line from
If there are multiple lines to read we
can use a loop
head lines
syntax bileobject headlines
This method heads all lines and Geturns them
in the form
of a list
write
writing on a
textile
write lines
write XYZ
fileobject write
writelines
file object writelines List variable
List variable line 1 linez line
Appending on a text file
write 11
write lines
Working with Binary files
To read write non simple things like
dictionaries tuples lists etc
objects
are serialized
Pinky
converting Python obj into byte stream
SIS Import pickle module
1
2 Open binary file in head write
3 mile
perform operations using
dump 1 and load I
4 Close the file