vse
(Muepes owen “pra
yoyo) 94 54 LOAN oH Lea ys
(© Scanned with OKEN Scanner2. Give the output ofthe folowing code stipe
nport paride
Sot, Vist? (2, 3, 4, 5, 6 7 9 301 Uh
LE(142==0 and 84-09
1502 append i)
f capent bindery cab)
plekle.dump(1ist2y £5
Felesed
open ("bin.dat®, rb")
dats = pickle. loadiei
for Indata
eines)
“0 Arathosbeenasted to dpa the amas of alstudens whohave scoredlss than 40 for Remedial Cass
re wserdetined neon to pay he names ofthe torts rom the binary fle Student. cat whe
Davee than a,
48. Flowing the structure ofeach econ a dat file nme PRODUCT Aa.
Iprod_code*; value, “prod dese": valve, "stock": value)
Theater prod cde and prod_ desc ra srngs andthe value for stocks an integer
Wee function in Python to update the fe witha ew value of stock. The stock ae the product. cole,
hoe stock sto be updated, ae to be pute durng ie execution of the function
45, Given abnary fie, STUDENT A, containing recor the folowing:
1S Aamo, 5_Nane, Percentage]
ier hese ee values ae
Sanne’ ~ Admission Number of student (tg)
Scams ~ Name of student sting).
Fercontage ~ parentage obtaned by studet et)
ite fanetion In Python that would reat the contents a the le STUDENT dt and tat would dipy
the deta of thore tients whose parentage sel 3.
46. wite a statement te ep binary fle C\Weyes\Tex tb end and write modes by speiyng fr fe
pahin so diferent fms
47. Wite a statement in Python to perform the fllowing operations
i) To epen tox ie BOOK at in read and append meses
(i) To open text le BOOK tin write mode
i) Te open tex fle BOOK in eppend mode
£48, Who lhe folowing code da?
File = open(*contacts.cay", "a")
ane = input "Please enter haze: *)
Fino = anput ("Please enter phone munber: ")
ata = (Hane, Pano}
covwriuer = cev.writer File)
comeiter.welterow (dats)
Filecelesen
45, vinta code 1 open the fle gven abe pesous question and print tin th
Name: ensme>” Phone
=75) ;
Eine (r(0),:(2)-¥12],sep="\") ]
fome=t i
except |
break
print ("\n Total no. of students whe have scored more than 798 mike:", mim)
fepjietose()
countkee 0
eS TE
1. whats the diference between’ and'¥ modes? |
2. Whats the sgnfeane of fle object? .
2: ow ae open() and cls) function diferent other than thelfanctianaty of opening anon ies?
© scanned with OKEN ScannerCASE-BASED/SOURCE-BASED INTEGRATED QUESTIONS
1 Sengeeta sa Python programmer woking na compuerhardvare company. he hast maintain the reccds
‘the perpherat devices. she created C5 le, eiphra sy, to stare dlls The stare of Penske
vis IP P_name, Price), where is Peripher device ID integer), P-name's Peripher dase ne
(sting) and rice is Peripheral device pice (tees (Cost 209)
Sangeeta want 0 write the following ver defied unetons
+ Aad Device): To accept a record trom the wt nd at to CSV hl Perpherales
+ Count.Device (): To count and display the nurber of peripheral devices whose pice Iles than 200,
Ans inpuct caw
et Ada ovicw (
cavfile -open (*Peripherat.esv*,
owritersesv writer (covfite)
P id-int (Seput ("Input Peripheral device 1D;*))
Fnamo= input ("Input Peripheral device nane:*)
P Pricesint (input (*raput Peripheral device pric
sevdatan(P_1d, name, P Price)
euriter.writerow devéata)
esvfile-close()
det Count evice():
cevTiLevopen ("Peripheral .esv
creader-csv. reader (esvfile)
for rec in ereade
Af int (rec(2}) < 1000:
cred
print ("Devices with price lose than 200
cevfile.close()
2. Genesis nfotechplans to develop a computer stem for payroll procesing of allits employees for string
‘lary details and furnishing celevant ans requ asin terms of total contribution towards ts employes
Develop a Python program which stores datain ‘employees, ealelates and dplay total salary renites
tits employees and displays the number of employees who ae draving 2 salary of more than S000
ith open ("employees cov") as esvfile:
jer = cav.reader (cevfule, deLimiter=",*)
“
ot
ne
print oc{O},"\t\e", eect] “V0
Sunt=int (e6e121)
HE Cant (200 [2111 2500
0c [2))
print ("Sum of Salary of alt employ
print (Em Salary>s000:", count)
es", sum
joyee Gettin
AOA 02018 10009
© scanned with OKEN Scannerlmport piekte Aseatemont 1
‘tet update rect
rece(
{dnmopen (myrize.dat*,*rh)
Fout=open (" ) AStatenont 2
found=Falze
‘ident Canput
while True
rece Astatenent 3
ator employee 10 to update salary : *))
if secT"enpld"joveia:
Foundeteve
rec{*aalary"Inint (inpot "Enter new salary : “)) q
pickle statement 4
suse:
ickle.dunp (ec, foot)
break
16 founde=teve
DEINE ("The salary of employee 10 *,eid,* haa been updated.)
else: |
Eint ("No employee with such 10 is found") |
Einelose()
Fovt close)
‘as, sport pickle ‘statement 1
of vpaate 2600)
seer)
Finmopen ("hyeite dat", "2b
fouteopen("temp.dat™,“wb") tstacenent 2
toundePalse
nay Ak Tet este intomatin n the ASC or koe formance,
Seasoning (Rk: In a txt fe, theres no ctnite essing,
38, Assertion (AA binary fe sores dt inthe sa
i Wa 381s stored in he memeey.
Searoning 5: Binary fein Python des not have ne debe
BO 2 way ae
et ne
20
SIN
2 New Heron Academy ha ven Rs ident a taht ate a
{rads es trom tet He ‘Newsletter TT and lon oe
examination eam hastens by
atthe code wil rn to fn the
method, FterWore
1 words WA ae In the
salem lanis in Beween the ease ns re enae
‘e108 10H Read the even Shon cae
fa wns
bef Palteswords (
thleropen 7 _") tStateément=t 5
for Cin statement a
Se ee
eh
(© Scanned with OKEN Scannerimport cov
fout = open "watch-cav", 'a"yaewbine:
We cov.writer (foxt)
Howeaterows ()
fout.close
print ("Records suceo!
Gee betete 0)
clock
found
Lnport cov
tin open(*wateh.cav', tr)
R~ cav. reader (£50)
> 1ist(R) f5n.close()
for sin
folly caved")
nput ("Enter Clock 1D to be renoved =")
Print ("Record to be removed is:*)
print (a)
Leronove(s)
break
it founde-False:
Print ("Record not found")
else:
Zout = open (*watch.cev', 'w" newline
W= cav.writer (fou)
Woweseerowe tt)
four-close()
print "Record Successfully Removed")
nite teve
Print ("1, Add Clock betadie")
print ("2. Reaove Clock Details")
Print "3. exit")
ch int Cinput ("enter your choke (2-31=
Sf cheei:
Insert)
elif chen?
Delete()
elif chew:
print ("Thanks for using this progran")
break
ele
print (*Incoreect Choice. Please re-enter")
MLS GLO LE OLS
and Ressoning. Each question has four choles
{0 (0, i), (only one of whichis correct. inthe ight ofthese statements choote the mart appropriate optic,
(0) Both Aad ave tue and Ris the correct explanation ofA
(i) Both A a Rare tae But Rs not the comet explanation ofA
(i) Ais ue bat is se
{iv) As fae but Ris tue.
© scanned with OKEN ScannerWH Amport ptedte
11 open Comp atten
'£Cotx}>=25000 and otnt=30000)
hat 9)
Hotosen
8 a with statement
‘Am with atementensires that aleve
‘we stop aig the fe tne ane
ith statement
55. A nay he,
He objects et destocatedsunaically once
‘exceptions abo, we ave not eauted to dove the he ep sree
"TRAN has he slowing site
Uno, mame Tee |
TNO~ Tain umber
NAME — Tel Nan
TVPE~ Tain Type
pecans tt detned func, tndtype (type), ha aces type as prameter aed diply a he
‘ecords om the binary fle TRAN da tat have the value o Tria Type aso,
Ans. det Cindtype (eyo)
1 open (mana .aat®, be)
uy
wot
‘data = piokie, toad (1)
SE datat2} == ttype
clot ("Train mamer :%, datatoy )
Print ("Train Mame :%, data()
print (*reain Type :*, datal2} )
fecloset
56, write menu-diven programinPiton hat defines and als he folowing functions:
Insert: Yo accept detalls of clack om the wser and stor
contains folowing fields ~ loch, ClctName,YearatMan, ee
‘stores them in the fein one go
Delete): To accept Cloci and remove the record with,
8V ile “watches. Each record of clock
8 Function takes deta ofa elacks and
ven Clock ram the fe watch loco is
fore removing the recor, shoul print the record
‘Ans. def Insect ():
teil
vse True:
ClockIO = input Center Clock 1D ==)
Clochnasa = snp ("Eater Clock Name = *)
Yearothant ~ bot (input ("Enter Year of Manufacture = *))
(renter Price = ")) i
As (Clock, Cloctiane, Yeatothant, price
append tt)
price = oat (i
more records (¥/1)=")
break
QUAD v0 0009 =
© scanned with OKEN Scanner(0) ¥ 10 create a CSV Fite by writing all Lines in one yes
det createcsv2()
4 open csv Fite
Covtite = open * student .cav",
# CSV Object for writing
Covob} seav writer (Cavetle)
Lines = 1)
white True!
no = int (Lnpot (*Rn0:") )
Name * input (*Hame:*)
Marks = float (input ("Karka")
hhines.append({Rno, Name, ark)
Ch = Input (Hore (4m) 2")
if Gh oe we
break
¥ Weiting 11 Lines in csv file
Ccsvobj.writerows (ines)
Covflle.close () # closing @ csv File
(4 # to read and show the content of 9 CV File
06 showall
4 opening CSV File for reading
Ceveile ~ open(*student.cav', 'e*, newlines!*)
# Reading the CSV content in object
Cavobj * cav-reador(Cavfsto)
For Line in Cevobj: Extracting Line by Line content
print (line)
covesie.close() # closing « av File
print ("CSV File Handling®)
while Teve:
option = anput
Sf option == "1":
Ceoatecsvi 0)
e1it option == "2"
Cewatecsv2()
\Createcsv 2:CreatocevAll J:thowe
00
elf option == "a"
Shown 0
break
(0 ite prowram that ead binary fe ‘en ad pay al he record of ernpoyees
(0) cg the records al he employees Who ave ekg salves betwee 25000. na
0 import picble “
£1 = open Comp dat, 4b)
© plebte. toad (ty
prints
N.closet
w by one,
|
:
|
(© Scanned with OKEN Scanner4% Hela a yt ste etn we st bir Me unt he
1 nue Mee, ne wa
Aa HL = md wet dat, ab)
esses‘ The tration
whe true!
‘yn stots dents 1")
yoo Caw Lap (kat Came")
men chawn otnt (igo MEMEE Gong wae Cda6ms)
ewe LM ie Hew vy 1 yet Aly og Hawt Thaw net ae,
easel
1 Chas0
PHeK Le sawp tiec, A)
eee awn ty
Hetewwe
a 12 ying» program to create C3V He “user co? which wil contain wername snd
ssw For sone enties He has wen the following code, As a programmer, help hin to succesatlly
ferecte the pve tah [USE Sample Cveston Paper 2020-23),
Fine
ond): Htowrlte / add data into uw c5Y £6
Hunersesyt,! oy Whine?
how Loli tar = sy. writer tt)
et
lowP Lele LLex wr iterov( sesame, Passtord])
fclowe() fowy Cle reading code
£ keaduavPl tet): 4H to v6ad data from C8V Cite
With open Cuser env", 14°) ap newPLte
uPLle) # Line 3
Wileteader = csv,
prtat (rom) 10411)
howl ile Hine 4
Aaco¥es Le (Arjun, 1210436")
addCov¥s te (*Arunina”, “arutnina”)
addCovPb Le ("Fr tea "myname tH")
reaacavPi tet) F bine
10) Name the mle We should port tne
(in whieh mate should Kao open the ile to add data nto the fe?
ii) F100 he bla tne $1. he data fom a C3 fe,
{iv} it he blank inte acne thee,
(4) Yate the cup he eal obtan while exectig Une 5
hos jew
(0) Liner i a
(iH) Lined) render ~
Ww) Lined closet
(a) Ar june 12 0045
Aronia or udnin
Feieda myname!
(© Scanned with OKEN Scanner1 tetas th Nowacerer nett pen
‘ans. det progran_radom 0
Pe opentemerge txt, "2)
printtt-tel10)
fo seck (4,0)
eine (£4000 (5))
f seek (10, 0)
print (F.tell 0)
print (f-read(10))
progean_ sna)
29. ere tendo pusion the le phere the being fe fie Wie yen saemen for
‘same, assuming 'F is the fileobject. ee ee!
ns Feveekio) |
40, nicht he fowing le modes wlth exiting eta of ent elt
1, ab, w, web, ab, wb, wh+, we, r+ ‘
Ans. nf medes 2, band, the exiting ato the wl not eet
Whats 9 Ve?
Ans, CV Comm Sparated Valu singe le format sed tre tab umber ane sucht
2 ioeadiee or dntabose panto
42 at are the anges of 65 fle oma?
Ans. The lowing the advantages fC le forma:
(a) tesa simple, compact and ust forma or dts storage
(3) iia common format for deta tentang
[]Itcanbe opened in popiarsprentbe! packages ie MS Exe, et
(6) Near aspesdsheets and databases upper more CY tak .
43. Differentiate between a text file, a binary file and a CSV file. i
pm i
Toate nay erie .
1] capable of fading Ri paleo anng ae] Rar vey eommon Tomek and]
tential ata ex plc independent. i
7 [consis ofssererofines|[Remsssofctawiowecic| ens of phintea wana Ta] |
‘of a set of letters, numbers | pattern without any delimiter. | data with a delimiter. {
or symbols (steing). |
5 [aot iene [to see powans nea be ea ing ed es We] |
Cantevied toread data, ued to read dst, Pyton| Notepad andspreneseet swore, |_|
provides functions to read data. q
«iver te es wih EOE| Theres no spel OLR embatesanw anonatcahy when
chore saves the delete isnot sed ae et,
44. betine fonction veplace a paces to er with (Gah i
son cut vep,provianth r
ata = fleveed()
data.replace(? *,*=")
with open (*merge.txt™, "WP a8 £1
|
|
i
© scanned with OKEN Scanner
program)34, Write a function a Prthon to count the umber of ines which are starting withthe aiphabet An tot file
‘STORY. (CESE Sample Paper 2019-20)
‘Ans. def COUNTLINES ():
fle-open(*sToRY txt! "c1)
Lines = ¢ile.readi ines!)
count=0
for w in Lines:
ifwio}
AY or widl==tat:
Print ("Total lines:*, count)
tie-clesety
35. Wire @ method/tuntion, DISELAYHORDS (, In Python to read lines from tert fie “POEM tat and
splay those wards which are ss than 4 characters
‘Ans. Gof DISPLAYWOROS():
co
fLLewopen (POEM. TAT,r*)
Line = file.read()
word = line.split()
for w in word:
if Lentw=10" and student fi}er"9rs
ste_roll_no= str roll_no + student (1)
ea
4#Str object converted into integer type
3_rollno = int (atx, roll_no)
Checks if the entared roll number matches with file data
Af rell_no == @_rollne:
print ("student found: ", student, end="")
lag = true
break
Af fag == Fal
Print ("Record not found.")
else:
print ("File does not exist")
Get get_nena()
tprint menu
choice = int (Input ("Select a choice (1-4) :"))
return choice
def maint)
main Hen = Student Menu
1) Add new student record
2) Display student details
3) Search student.
4) Save and quit '**
choice = get_neau()
while choice !=4:
sf chotce == 1
student._record(t¢1ename}
elit choice == 2:
student _readdata (€4Lenane)
elit choice == 3
sturdent_search (€Lename)
print ("Invalid ehotee, try again")
choice = get_mena()
Af names"
© scanned with OKEN Scanneri ent roll_no, name and address, using the functions given below:
i 1 suerte se cs
‘student seachenane|—Searha student on the basi fol no
9 add nore records: ? s4)
med gad mode
© Scanned with OKEN Scanner{case 2014)
"SOOO" betore execution, what wil be te cones of the fle after execton of
ies would you need ta manare the fl
1 Yo proces fou fs sequenaby
ee rn
© scanned with OKEN Scannerrmodsle
eadrec=1
Feadreemreadrees]
except EOFError:
ropram oily al the ecard ns le slong with lne/record number.
‘ns. £ = open (*result.dat™, *")
count, ree) tho suppress extra nowline by print
ine readable format and to aecess the
ton. Python has ast of modules
at some destination which we can cl Back t 3
Is used forimplementing binary He structure,
ing binary Hes, respectively
functions to read He,
02818 tog o—@
a texte wrebnes)
© scanned with OKEN Scanner© scanned with OKEN Scanner
Me MYMOTES 1 and to dspay tore Fines which start
the sk ofthe binary file named
‘employee name, base salary and
sr oes 0-2-4906)18, Wat he dfnition of method MSEARCHSTATES)
with he alphabet 'M,
For example:
© scanned with OKEN Scanner‘Output: The line count sould be 2.
names and copies ll aes that do no tart with
‘gh Kimnopgrstuvwxyet
hore more Lines ¥/¥) :")
(© Scanned with OKEN ScannerHe ater temowng leading an ating whtespces.
on tht sep aatly counts and dsplas the numberof upper an
(cast 2026)
(© Scanned with OKEN Scannerlet open le named test er reaing whichis stored
ct
vil ob nn made
re" at. Conder the following code
ig
rector are the same. What wil be the absolute
hoo Sports/Acevements pg
hoo amination Achievements og
(faa ont mode
(W Reas.wite mode
the rng. For example, Unica text)
© scanned with OKEN Scanner4 me yt yi
ae ‘oh osm Oe
0 mt 0h si) 9 wor
1 ny pig 494M oo
7 te Reset 1h Maron Word) Wh EW) Senge ne
so et pm a dg an i 8
on 9 a owt tates As OH Med
0 few nn Carian 1) comme
tae 9) sh Space
WF pen ang say ie ie, Ve oe hare, WA A NR
mse ina wie 1H) Rentine ener
© scanned with OKEN ScannerIn both append modo vead mde
and he fle onthe sak,
inthe oder. otherwise, Python wire FeNotound
it fle mode write mote
ring len append mode erates the previous ta
Imported into the program for reaing 2 CSV le
be performed on fle depends upon thefie mode In whichis opened
() The cet argument to see) methad indicates the umber of bytes tobe moved.
(0) Ifthe ot val is et to 2, the begonng ofthe le would he taken as eck position,
(i) append {ry Nonecttnese
bet, which method the best for eading the wate feito
(0) read (0) vend) (1 eeasines7
{6 Consider he folowing Python (c0se 2028)
F. seek (0, 21
(© Scanned with OKEN Scanner© scanned with OKEN Scanner~
1 en ts beh ts ve on ae ag dees adh, pe ee
1 ess edn wT He ary
(© Scanned with OKEN Scanner© Scanned with OKEN Scanner© Scanned with OKEN ScannerContents mares etd
errr
fia] Hy aed
(© Scanned with OKEN Scanner© Scanned with OKEN Scanner© Scanned with OKEN Scannerre fe nvand mode. Te fe Obet named € The Mleaheee ls |
above code we first open he OY Ihe ovens) O)6 a ev reader() The eaderablect |
converted a conreade one cove Now, we iterate through all herows usingafirlonps |
ised tread res a ro nothing But a is contig al he ld
When we try to print each row, one can find th af
aoe thus, all the records are displayed as lists separated by Comma,
tn the net implementation, we will count the numberof records present inside the studenten fle.
Practical Implementztion-27
inte a program to read the contents of stdent.sv fle using with pen() method
:
eet |
: Ceoarareaee ee
J
Te above modified code uses with opent function, the only difference being thatthe ile being openest
‘sing wit open() gets automatically closed after the program execution gets over unlike open() where
we need to give close() statement explicit
Practical Implementation-1
Wire a program to count the number of records present in student.csv file,
\Wrythce program to count Ue number of Fecords prevent in Vatudeat cay" File
sport ery
(repent ataaent cv",
eadar = env teadei(€) #oav readers the cev reader object.
Son
we |
ft elena() Mapiioitiy closing the thie
~— Qin ern
(© Scanned with OKEN Scanner(in) Ck Save bat
(WW) Nest step isto open the Notepad and open student.cav ile that contains equivalent data for
‘student alsin comma separated values.
students
In studentcsv (notepad) fle, the first line i the header and remaining lines are the data/records.
“The fields are separated by comma, oF we may say the separator character. In general, the separator
‘character Is called a delimiter, and the comma is not the only one used. Other popular delimiters
Include the tab (\t), colon ()) and semi-colon (;) characters
Practical implementation-26
(Write a program to read the contents of student.csv file
(© Scanned with OKEN ScannerCOV es are commonly sued tease (ey 3° 8910 ad and manag, small fn tad as
process/nfer Reco ofthese sant ares they ar fequent ued stat epleong,
ee epanes ton sins ccoamere exe © aol er
Trace crconmmarcsputernstnown ors pyar CEM anna ‘example
Thus, ina mutshell, the several advantages that are offered by CSV files are as flows:
CSV sus ike a text le and is faster to ar
CSViesmaller in size
CSV is easy to generate and import to a spreadsheet or database,
(CSV ishuman-ceadable and easy ce et manually,
CSV s simple to implement and parse.
essed by almost all exis
1 pplications.
er understanding the concept and importance of using CSV files, we will now discuss the read and
te operations on CSV files.
#14 CSV FILE HANDLING IN PYTHON
For working with CSV files in Python, thee san inbuilt module called csv. It is use to read and write
‘obular data in CSV format.
Therefore, to perform read and write operations with CSV ile, we must import esv medule.
‘sw module can handle CSV files correctly regardless of the operating system on which the fles were
created.
‘Along with this module, epen() function is wsed to open a CSV file and return file abject. We load the
‘module in the usual way using import:
>>> import csv
uke other files (text and binary) in Python, there are two basic operations that canbe carried out on,
csv fle:
1. Reading from a CSV file
2 Wilting to a CSV fle
Letus discuss these CSV operations.
4.14.1 Reading from a CSV File
‘Reading from a CSV file is done using the reader object. The CSV filets opened as. text Ale with
‘Python's built-in opens) function, which returns afl object. This creaies a specal type of object
tw access the CSV file (reader objec) using the reader() function,
‘The reader object Is an iterable that gives us access to each line of the CSV file as ist of Meld.
‘We cam also use next() directly on it to read the next line of te CSV fil, or we ean teat i ike a
{ist mn a for loop to vead all the lines ofthe file (as lists ofthe file’ S
“This shown in Practical implementation-26.
(0, Before this, enter the student details in spreadsheet and select File > Save As option
{Gi) Type the name of the file as stent and select CSV (comma delimited) (CSV) format from
Save AS type option.
a
ie
(© Scanned with OKEN Scanner© scanned with OKEN Scannertel0.
© scanned with OKEN Scanner
4.12 INTRODUCTION TO CSV
\c today’ organizational woking environment, data sharing son ofthe major tasks tobe carried
sadsheets or databases,
Fig 49° Stage Format
@—+___— oe(© Scanned with OKEN Scannerwhich ignfes seek sreative
ion. and 2, which means seeks relative tothe end of le There iso
Relative referencing/posiioning has two arguments, offset and the position from which it has to
craven
‘he symtax for relative reerencingis:
suk (ott
20.1) from current postion moves 20 bytes backward
{e¢k(100) fom beginning of file moves 10 bytes forwant
{eti()—tel() returns the current poston ofthe fe read/write punter with the fle. tf we have
‘moved ourile pointer through sek() tl) is used tel the position where le pointer iscurety
point
oe can sen Qe
(© Scanned with OKEN Scanner‘iC i
© scanned with OKEN Scanneré a anne ne snnnniinenes eae
(© Scanned with OKEN ScannerPractical implementation-23
‘Program to search a record from the binary fle student.dat on the bass of roll number.
nc the rad own the le pointers mere he begin othe le sing see)
statement
and then be hanged name writen thee andthe eer
er an ate. apeh( meted se
We wil be learning mre abou it ithe nex section
ii
© scanned with OKEN Scanner© Scanned with OKEN Scanner(© Scanned with OKEN Scannereat eter ace ate
© scanned with OKEN ScannerAle bin Me.dat.
bet from pickled fle
sto be cased using import
>>> oud = os .getend()
>>> print (cw)
Files are always stored in the current folder/direcory by default. The os (Operating System)
‘module of Python provides various methods to work with file and folder/directories. For using
these functions, we have to Import os module in our program.
cowd stands for current working directory
A string lke cwd that identifies a file is called a path, A relative path stars from the current
directory, whereas an absolute path starts from the topmost directory inthe ile system.
For example, the tet fil we have crested inthe previous programs was opened through the
absolute path
(© Scanned with OKEN Scannerele
|
With the Rep of lowe chart, we can tore data inside a Mle using a spec
wed repent he string of nl carl |
Practica Implementation-14
vod code a program that asks the user to input their name along with age and store the
as o/s A/neponta/tocss/trogtam/Python/Fytondia/e |
+
© scanned with OKEN Scannerhe close method wl
ot eased.
4 TAPPENDING TO FILE
Append means to add to sol we want t add more data toa ile whic already has some dat in
"te wall be appending data In sucha case, use the access mode ‘a which means
“Open for writing, and ifit exists, then append data to the end of the file:
1m Python, we can use thes’ mode to open an output ie in append made. This means that:
> Ifthe file aeady exists, it will not be erase.
> Ifthe le does not exist, wil be created.
> When datas written to the ile, it wil be writen atthe end ofthe e's current contents
Syntax:
= open (,"8")
Here, ‘a stands for append mode, which allows to add data tothe end of existing data instead of
overwriting inte file.
For example,
>>> = open("testl.txt*, "at
Practical Implementation-13,
Program to add data to an existing file.
((Freopean to aad outa to existing ata ie Ghe Alle
open (*tast.txt*, 1") fopentag £836 $0 append mode
Eretivelsinpie syntax ot the Tangeage
Ecreitg (mater ython pomane ey to feud and write)
Paisteo
‘output:
oo}
(© Scanned with OKEN Scannercist) method in al the programs to las the
ae we cept using lse(), there fsamaltersative
moet which canbe weed in the programe, Will statement which we wl JSG NOH
en()fanctlon for ereaton of fe, with tatement can also be used forthe same ]
‘statement to group fle operation statements within black to make the
r= readable. This method is quite handy when we have two related
1 would ike # execute ae 3 pair wth blocks of codes in between.
Practical Implementation-12
Program to lustrate with statement,
=e ee
(Soperenitea’, SY
soecseatcrytnen
Eestecheegee
irate worn en \)
sits hie ceed Settee |
Output:
eae a
Ze file closed now: True
Contents of text fle test txt
“has the advantages of wing wth statement ae
t ithandis al the exception occuring before the en ofthe loc (which generally ae: Eni of
the fie ror and stack undertow), i
2. ttavtmstically cose the fle and releases the resources allocated tothe file
‘Therefore, based on the concepts learnt sofa, certain important points shout be kept ip mind
vile working with fs in Python.
——— ea
(© Scanned with OKEN ScannerThe content ofthe Me al)
Homies ts
omen 34
om Ete nombre ap
1m the above program ‘+! ope
type conversion trom ai
2. writetines(): For writing string at atime, we use write) method, ean he used fr iting a
Tis. tuple. et. into he Sequence datatype such a Hs, ple, ee, Including multiple strings
be wit we tine sng weitelines() method in the ent file
The sym
for weritetines()
So, whenever we have to writea sequence of string/daa type, we must use wetelines() instead
‘of write). writelines) metho accepts any type of sequence as an argument
Practical Implementation: 11
Program to add ist stems toa ie using wetteines() method,
Lise sUccoopucer acience\ne, "Phyetoe\n®, “chembatey\ne, “Matne")
| ecersteninen ise)
[bHIne (cuit oe tines write
to the tite successtuliy")
output:
Jeune oe Ttses weit
Contents of text fle test4axt
the fl, the cursor always tarts from the beginning of the fle
‘Aiso to be noted hore is that writelines) method does not add any EOL character to the end of
sates Nabe doi ourselves. So, toresolve this problem, we have wsed“\n’ new line character
the program) after the end of each Us tem or string,
ARON 2 1 909 ———__ a s ‘
(© Scanned with OKEN ScannerInthe above example, ater he program gets executed! andthe data (both string as wellas mere)
{sets written tthe ile the blinking cursor inthe Python shell indcates that the data has been
successfully writen ont the file newtest xt
‘CTW: While witing data to a fg alg UNE MARCO nethod| we nl Be INE new ti |
‘eed, otherwise the ene data sale wien na snl ie
Example 6
‘To perform addition of two numbers infil
= |
| Exeiee an)
evita na)
fette(aan)
Pile sc: \oners\Ueer4\appoata\ocal\Propeams\Python\nytnenati\ython 8.px", Line 5,
‘eerie (numa)
lpvpateror write!) argument must be at,
1 above code will generate an error and no values are written tothe fle. This is because writing
‘pumbersisnotpermittedtoatflle thusitisrequted tobe converted intoastringirt.
‘To perform addition of two numbers using file (Moification of Frample 6).
[reopen (stnes ote, '') i
Joanne gat (rater the first womber)}
eee se logue enter the second mber:"))
‘saminnumt oom |
| Eeritar'\n meer 1
Eivektet\n momber 2 :
[ecerteat\e fon ot tw sme
(num)
im)
state (wumi))
floes) i
*) e tnt set 90
(© Scanned with OKEN Scanner© Scanned with OKEN ScannerPractical implementation-&
Wiite a funtion tst() to rea a tet fe alpha txt and display those tines which begin with the
word "You"
ne TT
faa celeste
| i eee eee
| emesis
a
(- nestants c:/0seea/8@/Agpoeta/
fEvours tare"s “working’r with exe’, “¢hle')
eeniay 2 Syenon'T
4.6 WRITING TO FILE
‘We can write character data into file in Python by using the following two file object methoxis:
1. write(string)
2. writelines(sequence of lines)
1 write(string); write(string) method takes a. string
{as parameter) and writes i in the text ile ina single line
For storing data with end of line character, we will have
to add “Ww character to the end ofthe string. Notice the
‘addition of "a atthe end of every sentence while talking
of data.t('\n Is treated as special characters of2 bytes).
‘As argument to the function has to be string, fr storing
numeric value, we have to convert itt string.
(© Scanned with OKEN ScannerContents of words.xt
|
|
| ras te
| PS a se
letcoe naemn st seent
Practica implementation 7
Program with user defined function vowel count) tht conte snd deplay the numberof viele
An the text file poem.ext.
em meni cntacaoncpi mH a7
ot vowel_count()
eine (tho ot vows! yeoune)
felosen)
\vowe)_count 0
= . weno
ane Sa,
| SS ee SS ~
[accor warn eso )
ee
(© Scanned with OKEN ScannerProgram to display the contents of the file starting from 3% character into the list.
| ferogram to read data from
=i
Practical Implementation-6
Program with user defined function ¢_words() that separately counts and displays the number of
uppercase and lowercase alphabets in a text ile words.txt.
amino amanactor me a
IP esegram wits seer defined Function © pening nT SaSEaLy Sot .
| aoa aieplays the number of Uppercase and lovercase siphabets
fia texe fits words. exe
|det words:
pM te semen)
| 2 ehetamigha() ond cheisiower():
lewd
Ane (rus of pean
pelne (rns ot towercace Iettersle)
le wards (0
aL a
© scanned with OKEN ScannerTie, second call return the nent Hine, and 0
vena rom where reding/ ering of dts should happen
w/e new ine character) The new ine character
When end af les reached, reading)
ye returned and stared using vrabe as shown below
« ation
For reading an entire ile using readline), we wil have to lop over the file obec. This is &
Yin, simple a fst way of rea the le, Hk
a dat ine byline wing readin() method
wtp
J
(0): readines() faneion can b
nt all the lines presenti the file. 1 will start reading the data line-wise from tne
ing ofthe file and shal ply the contents ofthe etl the end of ile character
st read the extre content ofthe ile This method
10 the siz of memory required before sing
fh separated by new line character!
9 a
© scanned with OKEN Scanner%) readin) To ead
{6 darter neon nr oth cr te ee a
ead un te end of ele As he es missing has negate
, (av then he eee eat tow ie
readline: To read ont reat
NON ine fom the le; starts reading tom the crs wp a
{neluding. the end of ine character “a
4) readtines(): To rad
al ines from the fein st stars reading from the cursor wp the
nd ofthe le and returns
a of sengs, separated by new ine character \
‘ws understand these methods withthe help of suitable examples using a text file Test
1) read) /read( ste) read) function without sn argument canbe wed to read entire data wile
‘ead{sie) can be used to read specificste string from 3 file This function aso rears 2
‘string ead trom the le. A the end of he fl, again an empty string wil be returned
‘The syntax of ead) function i:
£ileobject.reaa) oF
fileobject..read((sizel)
Here, size specifies the numberof bytes tobe ed from tefl So the function may be ese 12
read a specific numberof character from thee the ale of sei not provided ora negate
le specified a ine, then the entire willbe read One must tae care ofthe memory 86
amlale before readig the entre content rm the le
Practical implementaton-1
“Toltustrate read uncon by reading the ete data from a fe (test
a °
a.
(© Scanned with OKEN Scanner1en() meth sal be define
Let us assume thatthe ext ies resent in the dv, Then the
Note: Atle always pts opened in ead mode and as tet fe
Let ws discuss these properties of File Object
File object
my reated, we can retrieve val
‘that le using associated propert
1. name: Name ofthe opened Me
sod: Mode in which the ile gets opened
ek closed or nat
oft Windows 05
3. closed: returns Boolean value, which indicates whether
le (Mir
by dau)
4.5 READING FROM A FILE
Fython provides various methods asiocated with ie objet for reading data fom ale, We can
le by ving the following read methods
hele sats reading hom the cursor (inthe begining
ea: Tovead the entre data
the fe) up tthe end ofthe Me
ene Creating Bie
> Traversingaf
for slaying data on screen
> Appending data ina fle
> Inserting data inafle
> Deleting data froma fle
> Creating a copy fle
> Updating data ina fle
su his chapter, we shall be resting outst three major Me operations, vz reading, writ
Hi pening co the file Resto the operations are beynd the scope oe syabue, Se
—Q-*
amt Scene wn htt
© scanned with OKEN ScannerOli Data File Handling
4.1 INTRODUCTION
© scanned with OKEN Scanner