Problem Solving and Programming
CSE1001
Prof. Ramesh Ragala
October 14, 2016
Prof. Ramesh Ragala CSE1001 October 14, 2016 1 / 21
Introduction to FILE HANDLING
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.
Prof. Ramesh Ragala CSE1001 October 14, 2016 2 / 21
FILE HANDLING
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
Prof. Ramesh Ragala CSE1001 October 14, 2016 3 / 21
FILE HANDLING
Prof. Ramesh Ragala CSE1001 October 14, 2016 4 / 21
FILE HANDLING
Prof. Ramesh Ragala CSE1001 October 14, 2016 5 / 21
FILE HANDLING
Input / Output
Input is any information provided to the program
Keyboard input
Mouse input
File input
Sensor input (microphone, camera, photo cell, etc.)
Output is any information (or effect) that a program produces:
sounds, lights, pictures, text, motion, etc.
on a screen, in a file, on a disk or tape, etc.
Prof. Ramesh Ragala CSE1001 October 14, 2016 6 / 21
FILE HANDLING
Kinds of Input and Output
What kinds of Input and Output have we knew
print (to the console)
input (from the keyboard)
So far ...
Input: keyboard input only
Output: graphical and text output transmitted to the computer screen
Any other means of I/O?
Prof. Ramesh Ragala CSE1001 October 14, 2016 7 / 21
FILE HANDLING
Necessity of Files
Small businesses accumulate various types of data, such as financial
information related to revenues and expenses and data about
employees, customers and vendors.
Traditional file organization describes storing data in paper files,
within folders and filing cabinets.
Electronic file organization is a common alternative to paper filing;
each system has its benefits and drawbacks.
Prof. Ramesh Ragala CSE1001 October 14, 2016 8 / 21
FILE HANDLING
What is a file?
A file is some information or data which stays??? in the computer
storage devices. We already know about different kinds of file, like
music files, video files, text files, etc.
Prof. Ramesh Ragala CSE1001 October 14, 2016 9 / 21
FILE HANDLING
Introduction to file handling
Files - Huge volume or Collection of data
Types - Binary, Raw, Text, etc.
Open any file before read/write.
Prof. Ramesh Ragala CSE1001 October 14, 2016 10 / 21
FILE HANDLING
Opening a File
file object = open(file name, [access mode],[buffering])
Modes of opening a File:
r - Reading only
r+ - Both Read/Write
w - Writing only
w+ - Both Read/Write
A - Appending
a+ - Appending/Reading
Buffering: If the buffering value is set to 0, no buffering takes place. If
the buffering value is 1, line buffering is performed while accessing a file. If
you specify the buffering value as an integer greater than 1, then buffering
action is performed with the indicated buffer size.
Prof. Ramesh Ragala CSE1001 October 14, 2016 11 / 21
FILE HANDLING
File Object Attributes
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.
Prof. Ramesh Ragala CSE1001 October 14, 2016 12 / 21
FILE HANDLING
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 )
Prof. Ramesh Ragala CSE1001 October 14, 2016 13 / 21
FILE HANDLING
Functions for file Handling
The read functions contains different methods:
read() # return one big string
readline() #return one line at a time
readlines() #returns a list of lines
This method writes a sequence of strings to the file.
write () # Used to write a fixed sequence of characters to a file
writelines() # writelines can write a list of strings.
The append function is used to append to the file instead of
overwriting it.
To append to an existing file, simply open the file in append mode
(”a”):
When you’re done with a file, use close() to close it and free up any
system resources taken up by the open file.
Prof. Ramesh Ragala CSE1001 October 14, 2016 14 / 21
FILE HANDLING
Functions Operation Examples
To open a text file, use:
fh = open(”hello.txt”, ”r”)
To read a text file, use:
fh = open(”hello.txt”,”r”)
print (fh.read() )
To read one line at a time, use:
fh = open(”hello.txt”, ”r”)
print (fh.readline() )
To read a list of lines use:
fh = open(”hello.txt.”, ”r”)
print (fh.readlines() )
Prof. Ramesh Ragala CSE1001 October 14, 2016 15 / 21
FILE HANDLING
Functions Operation Examples
To write to a file, use:
fh = open(”hello.txt”,”w”)
fh.write(”Hello World”)
fh.close()
To write to a file, use:
fh = open(”hello.txt”, ”w”)
lines of text = [”a line of text”, ”another line of text”, ”a third line”]
fh.writelines(lines of text)
fh.close()
To append to file, use:
fh = open(”Hello.txt”, ”a”)
fh.write(”Hello World again”)
fh.close ()
Prof. Ramesh Ragala CSE1001 October 14, 2016 16 / 21
FILE HANDLING
Playing Randomly in files
fileObject.tell() -> current position within a file
fileObject.seek(offset [,from]) -> Move to new file position.
Argument offset is a byte count.
Optional argument whence defaults to 0 (offset from start of file, offset
should be >= 0); other values are 1 (move relative to current position,
positive or negative), and 2 (move relative to end of file, usually
negative, although many platforms allow seeking beyond the end of a
file)
Prof. Ramesh Ragala CSE1001 October 14, 2016 17 / 21
FILE HANDLING
Example for random seeking
fobj = open(’/tmp/tempfile’, ’w’)
fobj.write(’0123456789abcdef’)
fobj.close()
fobj = open(’/tmp/tempfile’)
fobj.tell() # tell us the offset position
0L
fobj.seek(5) # Goto 5th byte
fobj.tell()
5L
fobj.read(1) #Read 1 byte
’5’
fobj.seek(-3, 2) # goto 3rd byte from the end
fobj.read() # Read till the end of the file
’def’
Prof. Ramesh Ragala CSE1001 October 14, 2016 18 / 21
FILE HANDLING
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 ()
Prof. Ramesh Ragala CSE1001 October 14, 2016 19 / 21
FILE HANDLING
Tips and Tricks makes it Easier ...
Number of characters in a file is same as the length of its contents.
def charcount(filename):
return len(open(filename).read())
Number of words in a file can be found by splitting the contents of
the file.
def wordcount(filename):
return len(open(filename).read().split())
Number of lines in a file can be found from readlines method.
def linecount(filename):
return len(open(filename).readlines())
Prof. Ramesh Ragala CSE1001 October 14, 2016 20 / 21
Prof. Ramesh Ragala CSE1001 October 14, 2016 21 / 21