Name:M.
Priya Dharshini
Rollno:24ITB21
Ex.No9.Implementingreal-time/technicalapplicationsusingFilehandling
Ai
m
Theaimofthisexerciseistowritepythonscriptforimplementingthegivenprograms
(scripts)usingfilehandlingandexecutethesameinPythonIDLE(throughScriptorDevelop
mentMode).
ProblemsGiven
Copyfromonefiletoanother
Wordcount
Longestword
Concepts
InvolvedFi
le:
● File is a named location on the system storage which records data for later access.
Itenables persistentstoragein anon-volatilememory i.e., Hard Disk.
● Generally we divide files in two categories, text file and binary file. Text files
aresimple text whereas; the binary files contain binary data which is only readable
bycomputer.
FileOperations:
● InPython,thereisnoneedforimportingexternallibrarytoreadandwritefiles.
● Pythonprovidesabuilt-infunctionforopening,writingandreadingfiles.Hence,inPython
therearefour basicfile-related operations.
● Theyare:
Openingafile
Readingfromafile
Writingto afile Processdata
Closingafile
Syntax:
● Openingafile:
fileObject=open(file_name[,access_mode][,buffering])
Where,
● file_name □ It is a string value which contains the name of the file
toaccess.
● access_mode□ It determinesthe mode (read,write,append,etc.,)inwhich
the file has to be opened. It is an optionalparameter the read
®modeisthedefaultfileaccessmode.
● buffering □ When the buffering value is set to 0, no buffering occurs. If
itis setto 1,linebufferingis performedwhen accessingafile.
Name:M.Priya Dharshini
Rollno:24ITB21
● If the buffering value is an integer greater than 1, action is performed
withthe indicated buffer size. If it is negative, the buffer size is the
systemdefaultbehavior.
Differentmodesforopeninga file:
● While opening a file, we can specify whether to read (r), write (w)
orappend (a) data to the file and also to specify whether to open in text
orbinarymode.
● The default way of opening is in read (text mode). In text mode, we
getstrings while reading from the file. In binary mode, it returns bytes and
areusedwith non-textfileslike.jpeg or .exefile.
● Thedifferentmodesforopeningafileareasfollow:
o r□defaultmodeforopeningafileinreadonlyformat.
o rb□Itopensthefile forreadonlypurposeinbinaryformat.
o r+□Itopensafileforbothreadingandwritingpurposeintextformat.
o rb+□Itopens
afileforbothreadingandwritingpurposeinbinaryformat.
o w□Itopensafileforwriteonlypurposeintextformat.
o wb□Itopensafileforwriteonlypurposeinbinaryformat.
o w+□Itopensafileforboth readingand writingpurposein textformat.
o wb+□Itopensafileforbothreadingandwritingpurposeinbinaryforma
t.
o a□Itopensafileforappendingthedatatothefile.
o ab□Itopens afileforappendingthedatainbinaryformat.
o a+□Itopensafileforbothappendingandreadingdatatoandfromthefile
.
o ab+□Itopensafileforbothappendingandreadingdatainbinaryformat
.
Example:
#Openfileinreadmode,thedefaultmode:
>>>file=open(“sample.txt”)
>>>file=open(“sample.txt”,’w’)#WriteMode#R
ead andwritefilesinbinary mode
>>>file=open(“sam.bmp”,’rb+’)
● Writingtoafile:
fileObject.write(str);
Here,stristhecontenttobewritteninopened
fileExample:
file=open(“sample.txt”,
“w”)file.write(“InformationTechnolog
y\n”)
file.write(“VelammalCollegeofEnggandTech\n\
n”)file.write(“Madurai\n”)
Name:M.Priya Dharshini
Rollno:24ITB21
● ReadingDatafromafile:
fileObject.read([size])
Here,sizeis theoptionalnumericargumentandreturns
aquantityofdataequalto size.
Example:
>>>file=open(“sample.txt”,‘r’,encoding=’utf-8’)
>>>file.read(5)
#Readthefirst5data‘Infor’
>>>file.read(6)
#Readthenext6data‘mation’
fileObject.readline([size])
Here,sizeis theoptionalnumericargumentandreturns
aquantityofdataequalto size.
Example:
>>>file.readline( )‘Inform
ationTechnology’
>>>file.readline()
‘VelammalCollegeofEnggandTech\n\n’
>>>file.readline( )‘Madura
i\n’
>>>file.readline( )
‘‘
fileObject.readlines([size])
Here,sizeis theoptionalnumericargumentandreturns
aquantityofdataequalto size.
Example:
>>>file.readlines()
[‘Information Technology\n’,’Velmmal College of Engg
andTech\n\n’,’Madurai\’]
● Closing a file:
fileObject.close( )Example
:
p=open(“sample.txt”,”wb”)
#Openafileforwritinginbinaryformatprint(“Nameof file:“, p.name)
p.close( )print(“Fil
eclosed”)
Output:
Nameoffile:sample.txtFile
closed
Name:M.Priya Dharshini
Rollno:24ITB21
SCRIPT
9.1 Copyfromonefiletoanother
OUTPUT:
9.2-WORD COUNT:
Name:M.Priya Dharshini
Rollno:24ITB21
OUTPUT:
9.3LONGEST
WORD:
OUTPUT:
Name:M.Priya Dharshini
Rollno:24ITB21
Result:
Thus,implementingthegivenprograms(scripts)usingfilehandlingwereexecutedandverifiedsuccessf
ully.
Name:M.Priya Dharshini
Rollno:24ITB21
Ex.No10.Implementingreal-time/technicalapplicationsusingExceptionhandlingAim
The aim of this exercise is to write python script for implementing the given
programs(scripts) using exception handling and execute the same in Python IDLE (through
Script orDevelopmentMode).
ProblemsGiven
1. Dividebyzeroerror
2. Voter’sagevalidity
3. Studentmarkrangevalidation
ConceptsInvolved
Exception:
● Anexceptionisanirregularstatethatisoriginatedbyaruntimeerrorintheprogram.
● Pythonpresentstwoextremelyessentialfeaturestohandleanyunpredictableerror
inthePythonprograms andtoinsertdebuggingabilitiesinthem.
▪ ExceptionHandling(StandardExceptions)
▪ Assertions
● Anexceptionisanobjectthatstandsforanerror.Iftheexceptionobjectisnotfixedan
dhandledappropriately,theinterpreterwillshowanerrormessage.
● Error sourced by not following the appropriate syntax of the language
isknownassyntax error or parsingerror.
● Example:
>>>if
a<bOutp
ut:
SyntaxError:invalidsyntax
● Theerrorsthatoccurduringtheruntimearecalledexceptions.
● Runtime errors can take place, for example, a file does not present while
theprogramattempttoopenit(FileNotFoundError),functionreceivingaparametert
hathasarightdatatypebuthavinginappropriatevalue(ValueError), a module does
not available when the program strive to open it(ImportError)etc.,
● When these kinds of runtime error take place, Python produces an
exceptionobject. If the errors are not handled appropriately, it prints a trace
back to thaterrorwithseveralparticulars regarding whythaterrorhappened.
Name:M.Priya Dharshini
Rollno:24ITB21
SCRIPT
10.1 Divideby zero error
OUTPUT
10.2 Voter’sagevalidity
OUTPUT
1.
2.
3.
Name:M.Priya Dharshini
Rollno:24ITB21
10.3 Studentmarkrangevalidation
OUTPUT
1.
2.
3.
Name:M.Priya Dharshini
Rollno:24ITB21
Result:
Thus,implementingthegivenprograms(scripts)usingexceptionhandlingwereexecutedandverifiedsu
ccessfully.