File Python
File Python
CSE1001
FILE HANDLING
problem
Consider the following scenario
” You are asked to find the number of students who secured centum in
mathematics in their examination. A total of 6 lakhs students appeared for
the examinations and their results are available with us.”
The processing is typically supposed to be automatic and running on a
computer. As data are most helpful when presented systematically and in
fact educational to highlight their practicality.
FILE HANDLING
Pseudocode
OPEN file
REPEAT
READ each line of file
SET count = 0
PARSE the line
IF maths mark == 100 THEN
COMPUTE count as count + 1
END IF
until end of file is reached
PRINT count
Input / Output
Necessity of Files
What is a file?
Opening a File
file object = open(file name, [access mode],[buffering])
Attribute Discription
file.closed Returns True if file is closed, False otherwise
file.mode Returns Access mode with which file was
opened.
file.name Returns name of the file.
Example
#p r o c e d u r e t o Open a f i l e
f 1 = open ( ” n o t e . t x t ” , ”wb” )
p r i n t ( ”Name o f t h e f i l e : ” , f 1 . name )
p r i n t ( ” Closed or not : ” , f1 . c l o s e d )
p r i n t ( ” Opening mode : ” , f 1 . mode )
Example
import s y s
i f len ( sys . argv )!=3:
p r i n t ( ”Wrong p a r a m e n t e r ” )
p r i n t ( ” p y t h o n f i l e c o p y . py f i l e 1 f i l e 2 ”)
sys . e x i t (1)
f 1=open ( s y s . a r g v [ 1 ] , ” r ” )
s=f 1 . r e a d ( )
f1 . close ()
f 2=open ( s y s . a r g v [ 2 ] , ”w” )
f2 . write ( s )
f2 . close ()