0% found this document useful (0 votes)
6 views

File Handling

Computer. File handling topic

Uploaded by

rishabhchaurasiy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
6 views

File Handling

Computer. File handling topic

Uploaded by

rishabhchaurasiy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 25
“The text file can be of following 1YPES (Regular Text files. These are the typed. Here the newline ch files have a file ex (i) Delimited Text files. In these values, ie, after each value, 8, & «© When a tab characteris used to separ (Tab Separated Values files). These ate the valu 1 When the comma isu © (Comma Separated Values files). These files take the extension as For instance, havea look at following example 7) Pt al bak or fl car tn dy id mode (default mode) and attaches, aracter is stored to every value. “a a ‘ Haat in ead mode (because of" given a8 mode) and ider one more file-open statement | 1) — Pence (stored in folder ‘w” given as mode) and i 2 Alestect 1 a80 known as {flevonde in above file open statement, the file path contains double slashes in place of single slashes) ———_ these questions in your mind (i) What is mode or fle-mode ? | the open) function is a path to just the file name is given, the ile in the curtent folder. ‘© The second parameter ofthe open function corresponds toa mode which is typically read (' people or need to be ported best way to store program information, The binary files can take variety of extesions. Most SOT ‘non-text fie extensions (any application defined extension) are binary files 5.3 Opening and Closing Files © reading data Python provides b these functions on. 5.3.1 Opening Files In data file handling through Python, the function as per one © writing data to files appending data tofiks nctions to perform these tasks. But before you can perf You need to first open the ‘he pelarintrtta sng mes Try tee 0 ‘pea meng sind 1024 dance —— rig gpe mes comm 0 Reason being that Wil be treated a tab character and \4! con some platforms as numericcigit oF some eF#0F to give paths in filenames correctly are file is closed by calling the lose) method of ts eabject. Closing of le important. tomatically dosed atthe end of the program but ti good practice to get nto Tiles explicitly. Why ? Well the operating system may not write the can boost performance). What this means i that if the ts unexpectedly Ce na loose dort riepet funcon acomplshes tis ask and hes SS Tawi goer for on cee) hcion beaks So thccpat od eon ek te! 5.3.1 File Objec/File Handle File objects are used to read and write data toa file on disk The file object is used to obtain a reference tothe file on disk =e fandle>.close( ) ‘ort ot ene permed on at and open it for a numberof differen File object also called file-handle) through a flea 4 Python program can work with files stored on hardware. All ctions that you pao, ‘Master is opened vi fle-handle ‘the lowing sateen: Meer Or Bessie ANTS a Me coe mt edt fale pent ) sa builtin function (sed stand-alone) wile asl) #9 method case ree Pr ilohandle objet (on a datafile are performed through file-objecs. When you use fle open( J, Python stores the reference of ‘mentioned file in the fle-object. A fle-objct of Python is a stream of bytes where the data can be read ether byte by byte ‘or line by line or collectively. All this will be clear to you in the coming lines (under topic ~ File acess moves) 5.3.18 File Access Modes When Python opens afl, it needs to know the file-mode in which the fi file-mode governs the type of operations (such as read or write or appen file ic, it refers to how the file will be used once it’s opened. File modes supported by Pyar are being given in Table 51 Sern Wyn coe cn) inc few ce yr nny wy © Pr eo lo)? Th as 8 ‘hse is goat propa ace . Henney bee ma antl closet) is used. This fle dow ot a le saad le exits Py il rant iting dat and vet ee sn a bd th an 5.4 Working with Text Files wnt seam provi or eading and vt the open ils In is Se ro pt oy ig mis eee going to expl eto 5.4.1 Reading from Té sc from a data fle But before YOU Cn of rent fenton 0 ie nade. Most thon provides soa hed a flit ote rend from 2 fie, tins of yan ae sed Blew 21 2 COMPUTER SceNCE yy Tette 52 _ Python dato files — reading writing functions x Sno] Method’Syntax 1 |reaa() = 2 oe a Reumste valasrag: =e ioe ‘.read({n]) ve we specty numberof byes with ad) Python wil ad onthe pci mambo We tn fle The nest e20) wl seating vars oe aston et Co Slipper zsstates hs fact “The output produced by above code is ——— Be Zorming the tack, eg, following statement Be Fs ction wi oe he fl a ed occ rf ah eee ! Ae Remo fe 3. [readlines( ) Syntax .readlines() ‘The in sbove syntaxes is the file object holding open (ile’s reference. Let us consider some examples now. For the examples and explanations below, we are using a file namely ‘poem.txt storing the content shown in Fig. 52. Figure 5.2 Contents ofa sample file poem. ‘over $< FE HANOUNG. cate Snes Rel sort eye snopt3 Rang let ci! = le: 4(E :\poem. txt’, °°") ‘The output produced by the above code will prin the entire content of file poem.txt. we we work, we try to be better wwe work with full zest but, why 4 that we just don't know any Teter. : wwe still give our best. we vee have to steal, ms But, why 1s that we stiTI don't get a mea]. “The readtine() function reads te leading and tailing spaces (ifany) along with trailing newline character("\n’) also while reading the line. You can remove these leading and trailing white spaces (spaces or tabs or newlines) using strip() (without any argument) as explained below. Recall that strip() without any argument removes leading and trailing whitespaces. ‘There is another way of printing a file line byline. This is a simpler way where after opening & file you can browse through the Bile using its fle handle line by line by writing folowing code: ‘for in ¢fillehandle> = . (evar) Forinstance, for the above given file em. tr, if you write following code, it will print the entire The readin) function wil read afl line lines ee Seemann eras nt Alin is considered sil a newline charac produced by shove program. sing fo lop, then The output produced by above code isjust the same asthe output The reason behind this output is that when you iterate over a filehandle me work, me try to be better <——— tines * Sane pt heese a ; ial character called the newline Now that you are falar With hese ein facing eg per aig te Programs. te tine ofthe fe the lop variable will contain the gun p 5.1 Wiitea progam to deplay hese os fea byes q ce syfile = open(€:\poen.txt, “ry Toners ee off ren EOL hrc, ein nd srseyttesen) fore trading whe opaces print("Stze of the given file poen.txt ier) |] SIZ# of the given FiTe poes.txt 1s afte = open(€:\poen. txt, *F") “A print(stze, bytes") — 387 bytes wre ‘initially storing a space (any non-hone vg size=0 5 5,2 Write a program to display the number of ines inthe fe, tsize=0 bd ile stra: ayfale « open(r:\poen. tet, 1) ve strismyfile. s«myfile.readlines() eee tsize-teizes Sinecoue lan(s) aber of Vines in poes.txt 15 18 size = size ¢ len print (Munber of Lines in poen.txt 1s, Linecount) print Size of Fle FOL characters & blank Lines syfile.close() print ("The TOTAL size of ize) J syfile.close() 5.4.2 Weting onto Text Files ‘output produced by the above code fragment is : After working with file reading functions, lt us talk about the writing functions for data files Lol eS oo \. available in Python (See Table 53), Like reading functions the writing functions also work on size of file after removing all EOL characters & blank Vines : 360 ‘open files ie, the files that are opened and linked via a fle-object or fle-handle. ‘he TOTAL size of the File 1 387 Juiesa ons ae ya % All the above code fragments read the contents from file in a string. However, [nas ‘readline (notices in the end ofthe function), then the contents are read ina List Got nn next code fragment. a 1._| wite() | .write(stra) | wate suing eto fe rence by sflchands 2 | witlines) Gode Srippet 7 Renting the compte fein alist a a Fetes) sae vein) ne radial) Appending o File ee "6 ee Hi inex rtd, Pytaon rere aig Se. rt 8 vite 4 nor-existing fl. Tha means, for an existing file with the same name, the earlier data gets Mee art look a the output The readines() has read the entire file in alist of ‘where each line is stored as one string :) allowing you to add newer data into. You can also adda plus symbol (+) with file read mode to facilitate reading as well as writing. ‘That means, in Python, writing in files can take plac in following forms: (Inn existing file, while retaining its content (@) if the file has been opened in append mode ("3") to retain the old content. (©) ifthe file has been open in ‘r+ oat’ modes to facilitate reading as well as writing. {ef the file has been opened 1 write-only mod (era the Be ha Deen pen an we! mM cloret ) funtion on fil ‘Let us consider some examples NOW: Code Snippet 8 Create a file to hold some date -Fsteout = open(*Student dat", W') ) re wre tsp writ there ‘ihout ling ny ura charac yr wae clase) “The sample ran of above code is as shown below the same folder where this Python script/program ile in specific f can open the created file Fig. 5.46) shows the contents of file created through code snippet 5. ‘Foee 2 () File created thie a ee) iW mde (0) The write mode Is stored in the same as that of ile nici facia canes code Snippet 9 (This code is creating a different file than created with code snippet 8) lace of write) function which writes the content of iso, des not ad necline character, 0 you hav 8 ‘\pf) Zreer details for student 1 below : rol centaur ven eine Fle: Answer Letter ‘sis @ wonderful eter. Its impossible to think of sentence without it We know this will never occur, How mediocre our world would be without this single most powerful eter. Figure 5.5 The contents of fe Ano. Pp. ‘Wire program tread a text oC | open “Answer. ein by oe and play ech wont sepa y 2°. r*) ‘initially stored a space (anon-None value) ine() #one Line read from ile word using split) # rncenceneithout#it.# schoutethis#singlemmostepowerfulsTetters# COMPUTER SCIENCE Wi ayfile.close() 5.4.3. The flush( ) Function The flash) incon ear that whatever shld in (upabler writoon tte acta leo dik SAA removing Whterpaces ctr Reoding fom File read() and readline) functions discussed above, read data from file and retum tins form and the Jradlines() function returns the entire file content in alist where each lines item of the list. Ds ite progam red we and apa he cout of OWES a oro ‘ 3 | Next youneed ~~, pp 51 FE HANDING these read functions also read the leading and vt ; all {railing whitespaces ic, spaces or tabs or hes Sects, you want move a of sei sit) functions [strip spt ) ad pean eng whitespace ‘Recall that: ‘

. cours sotnee NT] ae 5 EONS ile Pointer in File Handling 5.4.5. Significance of File Pointer in 5, standard Input 0 ut and Error Streams 5! ‘Every file maintains a file pointer which tells the current position in the Fle where yaa sding wl tuk place (Ale pointer in his contest wos ke a Book mac ing pane sraemeone asks Ou t0 give input fo «PTA intra o y egy ay what Whenever you read something from the file or write onto a fil, then these fi things re you need for it ~ the Keyboard. Similarly, if someone involving Se pointer: EE det You kn which device i wl bedpned en demon ea = eR ine Keyboard is the standard input device and the monitor i cn sally say (0 this operation takes place atthe position of file pointer and (i) fepointer advances by the specified number of bytes | Figure 5.6 illustrates this process. Iti important to understand how a {file pointer works in Python files. The working of file-pointer has been described in Fig. 56. _ 1. hs open (Marks. txt") ‘open te fe apace te fener atthe beginnng of he fle (se below) Senta, any error if occurs is also displayed onthe monitor Soe mnie sah esror device. = ‘g standard input device (stdin) - reads from the keyboard standard output device (stdout) ~ prints tothe display and canbe = ‘ec s andand «9 standard error device (stderr) Same as stdout but normally only or eros Having enor ‘output separately allows the usero divert regular output ioaleandatlbe oe ea ‘error messages. ‘Do you know interally how these devices are implemented in Python? These andad devi: pe mplemented as files called standard stream. In Pytho, you an use hese sundrd san, files by using sys module. After importing, you can use these standard reams tdi sdoat nd stdert in the same way as you use other files. Ineresting : Standard Input, Output Devices os Files If you import sys module in your program then, sysstdinread() would let you red fram keyboard. This is because the Keyboard isthe standard input device linked to ysstdin Sarl, sysstdout.write() would let you write on the standard output device, He mont. spastin and sysstdout are standard input and standard output devices respectively treated as fs. alu] [a] e[s]-[sf>[-[oTs pola [s [i Ti Ly [rarer ineener anne (Now the ment read will sake j place atthe current postion of file- pointer. a swrite(Line2) sre write(*No errors occurred\n") fi 5.4.5A File Modes ond the Opening Posit ‘The position of a fle-pointer is governed by the flemode ed in, Following table] ‘opening position ofa fle-pointer as per filemode. oem oe Tobie 5.4 File modes ond opening postion of fe-ponter el [re modes we Wwe work, we try to be better No errors occurred *—— Ser sder abo dep! a = coger 5 PLE HANDUNG Now the directory BACKUP'S path will be : ts very handy when you have wo related operaions wig :\SALESYEARLY\BACRUP in betwee. The yt fr sing Wh statemen ‘As to reach BACKUP the sequence one has to follow is : under drive E, under root directory (Gist \), under SALES subdirectory of root, under YEARLY bes BACKUP directory. 1 subdirectory of SALES, there ‘similarly full name of ONE.VBP file under PROP subdirectory will be: :\ PROJECT\PROZZ\ONE. VEE + Parnnane refers to root directory 2 sequence of directory names which give you the hierarchy to acces a pag, and CASH.ACT;’s path will be df Sy Sy nae Le cert avin deo suc “ial ahha viestieebithcr' Sr ciocen! — foe oe ao eo ary Seen [Above mentioned pth names are Absolute Patinames as they whe te pret arecery intone pte tom he op mot el of dinctry Sree Beats pthc eto pt mats to Some ‘which means under current working folder, there is fle ‘TWOPAS. Similarly, path name for fle CLDAT will be Pique 5. Now the meaner ger sat nccunts te esNCLADAT & (PROB being working Foden ECT, EZASALES. and E:\act (CLDAT bn pore oder 0 format of pth canbe sven, COUNTS respectively. owen tn tet?) which mein nd rear oie ks te es _ nor SSCL Ste ee a here fet \ (back ooo rectory...] the previous one. 10 r00t directory and other (’\’s) separate: a direc a binary fle wil et rated when opened in an output file mode and it doesnot { ger 5 FE HANDUNG our That is, for the file modes, “w’, “w+”, “a, the fle will get created if t does file exists already, then the file modes “w" and “w+” will overwrite “a” will retain the contents ofthe file. ‘An open binary files closed in the same manner as you close any other fle, Le, as pedle.close() Let us now learn to work with pickle module’s methods to writefread into binary files. pe COMPUTER scence 1M 4 5.6 Working with Binary Files write cence eh i iia orm when aE iy re of Ping where» byte seas i overt ing th 4 6 anling ng produce the exact replica Othe original eea | these methods (eading inside ty . except blocks and using with Python provides the pile module ‘when we talk about reading fom binary files in section 863 Python's documentation, “The pic 5.62 Writing onto Binary File - Pickling ‘esericng a Python object \ ‘shal lam tous pickle module for reading/writing objects in binary fils. t Inorder to work with the pickle In order to write an object on to a binary file opened in the write mode, you should use dump( ) per the following syntax -be-uritten>, «file handle-of-open-File> ) you have a file open in handle filet and you want to write alist namely fist] in sn you may write -dump(14St2, #161) oj un write on fle pel i fl ha Pet * In the same way, you may write dictionaries, tuples oF any Inport pickle module ciher Python objet in binary file using dump) function (pen binary il inthe required fle mode (read mode or write mode) tea dictionary namely student ina file Praca alowsyouto pee bec (2) Process binary file by wrting/reading objects using pickle module’s methods. 2 you may write : swe atone a es ipa " meee eet a eng secs ig a ce os moter int stadt i big wrinenon ements, and case bles ete 561 Creoing/Opening/Closing Binary Files [Reopened th leh as Ped A i. sn fe Sabian the same way as you open any other file (a explained insti __ Now consider some example programs given below. “ : vith file modes to open a file in binary mode cs, 5.8 Wite a program to a binary fe called emp at and write ino it he employee deals of some TOPOM SEGRE oe) af ga in mk fl employees, avallabe in the for of cones. | Nexen oi ed the le modes bi pn rend mode i ina as is Ss ) tbe medule bu these erie desis BE sscpen binary fle. But as pr slabs we halon ome = -_ "mt 4 COMPUTER SCIENCE WI Figg | CF) cp 5 rue tne Sa, © frat mle et fetta | 5.4.2 Appending Record ssh bin write ogg Is and append the new records weno mle written in the file. Just as you normally writen binary file, ute Mt 6 spn Oe Or you write records while appending wing the same dept oma ede a or" function ofthe pickle module. ae program's folder and iyo 7 3 no, name and marks) from user and waite ont a he user and write ont the file as long as the user jow you some garbled, = Fm, ete se nnee Anarene Heep lew ST 9) Write a program to get student data (ol “The program shouldbe abe wo get data from ‘adeclare expty dictionary ‘open file 5.6.3. Reading from a Binary ‘Once you have written onto a file using pickle module's ump) (as we di in the previous lst ‘The sample run of above you have written onto file using pi if module asit would program is as shown here section), you need to read from the file using load() function of the pickle then unpickle the data coming from the file wing syntax : Fer 5 fe HANUNG BB ci se sere ating } a a ynde>) F ram below, we have used cas a In the prog ve used both the try. except block (in programs 5.11 and 5.12) with statement (in programs 5.13 and § od a file openin file-handle fout, z the wit 14) for working with the files. Ne ider the ad an object in nemp from: YOU wou lowing program that is readin 18 With the files. Now cons amma a fen ern fh eo a rom the file you created inthe previous program ) the read dota one nancy nem 511 doesthe same or you. It reads the objects writen by program, fem open te fl Empat (created in rogram 8, ead the objects write init and Following program vera and diay them, Butbefore the program 5.11 read the following box qa You can now we he eject wl way fe we pn teterertte lod om reaching EOF Now that you have an idea of how to read and write in binary files let us write a few more programs before we talk about searching in and updating the binary files. ‘open fle created and used in programs 5.9 and 5.10 and display ‘tohold read records close file faces bE. ‘COMPUTER SCIENCE van, : oper 5 FUE HANOUNG nail following program is just dong the same ising fan variable namely found that is False initially and stores True as son asthe sur tested for its value and accordingly the Py ‘is successful. In the end, this variable is 5.18 Wit «program o open fle p Gyn teres and search fo recat with rol numbers s 12 0 14 f fou, Toso pene ney fea wit 0G in ie smport pickle string ="TiS: eta sry teary threats sw first Line, This 4s second Line.” Fle msfleinf open i 5 190") sc.” #open binary file in read node ‘# List contains key values tobe searched for print(vFile successfully created") ste ove programas created binary le namely yfile.nfo that stored the given st binary format. : 5.14 wenes progam wd fom te le myflelnfo ese s Prone Pram we rg encountered, Le, play all the fext before he leer e)) ‘The output above is : mi produced by above program is as shown below : - LP 5.16 Read file st dat created in erie programs and day records having maks> 1 1 sins 4s my first Vine, This 45 sec ——— St x free leer eel * Tas" seport pi yates st ‘gaectare empty dictionary object totold read records rocess with the with Block record in stu dictionary from fin File handle sprint the read record aed 1 chi fil dat for marks > 82 ovary oecnog in fe Sa va pares a) ‘eroVIno": 1, "Name™= sgiat, ‘marks’: 83.57 search successful: 5.6.5 Updating in a Binary File 3 ‘You know that updating an object means changing is value(s) and storing it again, wooed ina file is similar and isa three-step process, which is: {@ Locate the record to be updated by searching for it (id Make changes in the loaded record in memory (the read record) iy Write back onto the fle atthe exact location of old record “You can easily perform the ist two steps by whatever you have learnt so far. But Ye ey Tow he lation ofthe ecard in the file and then ensring tha ene mriten i written atthe exact Iocation. Thus, we shal first talk about inthe ‘ab-ection how you ean obtain the location ofa record and how you can place the fon a specific location (requirements of updating ina file) 5.6.54 Accessing and Manipulating Location of File Pointer ~ Random Access Python provides two functions that help you manipulate the position of file-poiner you can read and write from desired position inthe fil. The two file-pointer location Of Python are tell() and seek). These functions work identically with the tex files the binary files. The tell) Function “The tell) function retums the current postion of file pointer in the file Its use as per following syntax : .tel() ‘where fle-objectis the handle ofthe open file, eg. if the file is opened with handle fin, then fin-tell( will give you the position of file pointer in the file ‘opened with the handle fin. Consider some examples, given below. Weare using the same file “Maris.txP" (Shown on the right) that ‘we created in earlier examples. : Inia fe poiner abe jally file-pointer's position is at : 9 ——— after previous read, current position of File-pointer : 3 \ sper aig 5 ‘fl pntrs poston #5 a 45 «FILE HANOUNG Now consider the following modified code tion OTE function changes the positon ofthe fle-pinter by The sal } functon ig the fle;pointr atthe specified posiionin the open file. ets the cure poston of fle pois inn open fl. And the flecbeceseh( fenton pace he ie pote at thespected by non open he 1s specified) 1 for curent poston of file-pontr(o move file pointer wt. curent postion oft) 2. for end of file 10 move fle pointer wt end of ile) file object isthe handle of open file. ‘The seek ) function changes the file pointer’s postion to a new fle position = start +offet with respect to the start position as specified by the mode specified. Consider the following examples : ‘fh open(*marks.txt*, “e*) i pl te fle pea 308 ye fom ening een ros il plac hl pea 5 hd of ee tartar : » vi ple fl pine 3p eind acd a eae ‘fn. seek(-30, 2) i ple th fp 5 fom hee ‘n.seek(30, 0) <———____ eee ma= 0 wil ple le pint a 5 es behind aca dotion) ‘seek (-5, 1) << fa pon ne COMPUTER SCIENCE YT Pio p: ‘With the above exam can mae he ile pointer forward a 9 direction (Y BB NERA vale ‘eahpostvevalee we jis that: Hr cneng you ne ein oe jinter is not poss! sed movement of epi © Baa engetthe COP) en et of eier sno pO trend ff Coe anpesbnst on te above ssl file pointer location functions. Code Snippet 1 Check the position of fle ras 74 characters including “\n’ at the end of every line and ths hos reading the enie fle the fle-pointer isa the end-of fle and thus showing 75. Code Snippet 21 Res ___ Funcions see) and te} wot "ery net od iar le. Following sub-section vill 5.558 Undoing Yaar no fie {ew at trey pdt poi nd Cree Sr mer mene y acne Ste gen ae no rtm mye ad (ii) Write back onto the file at the exact location of old record, » eh i. er 5 FUE HANOUNG cooler ‘To determine the exact location, the enhanced version of the updation process would be {Open file in read as well as write mode. (Important (i) Locate the record : ) Firstly store the position of file pointer (say rpos) before reading a record ) If found, your desired record's tart position is available in rpos (sored in step 2) Make changes in the record by changing its values in memory, as desiced Write back onto the file atthe exact location of old record. Place the file pointer atthe stored record poston (the exact location) using seek at pos, which wa toed instep (the exact location ofthe record being updated) (@) Write the modified record now. The previous sep is important and necessary 2° ny operation read or write takes place atthe current file pointers postion. SO the file pater must be atthe begining ofthe record to be over-eriten. Following example program illustrates this process. ip 5.17(a) Consider the binary file Studat storing student deals, which you created in earlier programs. ‘Write a program 1 update the records ofthe file Sadat so that those who have scored more than ma ‘81.0, get addtional bonus marks of 2 Pram ‘Note. Important statements have been highlighted. smport pickle ‘declare enpty dictionary object tohold read records {Fin = open(*Stu-dat!, b+!) <——— tis impr to open fle i mod ‘tread from the file ical ha ‘try: white True : pos = fin. tel1() eee «store File-pointer position before reading the record oe vm FALE HANDUNG COMMUTER SCENCE WA Py. coeo 5 ty: “The above program will lok forthe desired matching record (with marks > 81) and mag, changes init and write back into the file. ‘locate matching record ‘Gurnan’ —_ changes nade in the record “tplacethe File-poimter at te exact location ofthe record tu, Fin) lean the code of program 5.17() to display the contents of mexified fi, i wil show you the contents as need to get the size of record record in bytes isnot straight (€g. 595 r epickle ete). Covering ules here is beyond the scope of the book and ths | we advise you to use the method covered above. programs) Following exceptions may arise while working with the fceclare empty dictionary object tohold readreerds | PicklePicklingError Raised when an unpic Pickle-UnpicklingError Raised during unpickling if there is any problem (such ''0+°),_ open binary Fie in read and write mode as data corruption, access to). HANDUNG 228m 57.14. Role of Argument newline in Opening of csv Files while opening csv a ‘ne ‘pent ), you can specify an additional argument newline, which rgument role of newline argument is vi jow woul ine characters whe working wah es ae Pe now would choot & 5.7 Working with CSV Files ‘You know that CSV files are delimited columns as we see in spreadsheets 0 Sales are separates with comma. TYPi {O but modern implementations of CSV fl Goat yma. Each tne in a CSV files 2 data record ee end consists of one or more filds, separated BY commas (or the chosen delimiter. Since CSV files are the tet fils procedures on these and then spl Fipenon BUT there is a better way of handling CSV files Awhich is using eso module of Python. In this section, we are Soing to talk about how you can read and weit in CSV files Using the ese module methods. js an optional but python handle ni ‘As csv files are text files, while storing them, some types o translation of end of line (EOL) character as per the operating jou are working on etc. bhferent operating systems store EOL characes diferent The, MS-DOS. Gncluding windows and 052), UND and Macntash operating yt all use dierent characters 12 fesignate the end ofa line within a text fie. Following table 54 lists the EOL characters u different operating systems. so ‘Totl 54 £0 corcters wed n diferent operating stems. lations occur ~ such as can apply text fle falues using split( ) Python csv Module “The esv module of Python provides functionality to read and the reader and writ It provides to specific types of objets ~ writer objects read and CSV files, The csv module's reader and records in a CSV file ‘You will practically lear to use the reader and writer objects and the functions to read nd waite in Cv files in the coming sub-sections. But before you use esv module, make suo {import it in your program by giving a statement as smport csv 5.7.1 Opening/Closing CSV Files A CSV file is opened in the same way as you open any other text file (as explained in section 3 but make sure to do the following taro things | string ~ no space in quotes). the newline argument while writing onto acsv te @ csv file with no EOL translation and you ieee Sn erate podline =) (SV fle cpm in write made wih le hae SAS por 1 P, mewldne = "*)¢_ C50 fle pad n read mode wh file hae we) cove opnad in write mode wh fle had (2 ie a EOL roan) | Not only this seal for working across diferent platforms its ako useful when Same platorm fr wring and eading You will beable to appreciate the rol ofthe ‘when we talk about reading from the xfs. Program 521 onvards it will Let us now lear to work with sv module's methods to write / read into CSV les, > csv foal nnd josed in the same manner as you close any other 5.7.2 Writing in C: ‘Writing into cov files involves the conversion o and then storing i in the form of csy file, For wri arene of the syllabus, hence we shall not cover these in this chapter. the user data into the writable delimited form ting onto a csv files, you normally use the COMPUTER SCIENCE WITH Frthoy, = Following figure 58 illustrates this proces. ‘menor a(S cover objet >, [delimiter « ede taster characten]} {you sips armen comma wl eae te dlr ——— stuwitter + esy.writer(fh)¢—— "emt fle nh is fle hate mri In the above statement, delimiter argument is not specified. When you skip the delimiter argument, the vhich is comma, is used for separating characters. But 5 FE HANOUNG. fio) Obt user dat rm a Ma and form a Python sequence (listo tpl) out of «. (21, "Neelae", 79,0) : stur (wi) Once done, close the file, ‘You only need to write into the writer obj the work it wll do itself, ie, converting the the linked sy file ate a CSV fie store student dita (Rolla, Name, Maks), Obtain data from ft the le. re shove mopan wil cote + ov 6 ng, bby the name Studentesv Notepad, it will look like : Be at tome You can also create the nested sequence program ena matically by appending one record to a tut while Alivessgae” ‘writing using Writerows() function. Solved problem 4g. isi performs the same. Please note that til now we have created cv files without lie argument, which the new! smeans that EOL translation has taken placental ow ts inpone sr fe ealinene clear to you soon when we start programming in the following segion, CSV Files 2 cy fle involves loading of a fs a, paing ie, emevng ination digit Phoniatr nrg ko ea ey Fyhensnuence that can be fentedorer nvr ee Bone ca be ‘oop is a Python iterable, eg. lists, tuples, and For roding ft 8 le you otal boing acon On | 4 SOMPUTER SCIENCE wa : “— ner FE HANOUNG will see that Python has, ‘Now if you open the folder of your Python program You Python as creeds rotmuch egy IM tin one go. All you ned to do Greate anes equees ot ofthe then wrt sing te waters fact ; : ter weet che writs al given ows tthe CSV lee, to wrt following net ‘The esv.reader object does the opposite of esv.writer object. The cs.reader object loads data from the csv file, parses it, ie, removes the delimiters and returns the data in the form of a Python iterable wherefrom you can fetch one row of data at atime. (Fig. 59) (==) Ss : si Figure 5.9Role of csv.reader object. Let us now leam to read from fies, noder to ead from acs fle, you need o do the folowing. (Import csv module ‘The file being opened must already exist otherwise an exception will get raised. Your ‘code should be able to handle the exception ie, through try.except. (Alternatively you can use the with statement as mentioned below.) 1 the syntax as shown below , [delimiter OTE ; 7 ov es are tet es Following program is doing the same. a Pp 5.21 You created the fle compresultsv inthe previous program as shown below. ; Wie a program to read the cv file a sen oom oe he cord of his fe and display Nate. Before we write the code or this program, recall yoduce the result as ‘Compare the above output with the sample run of previous program (program 520). We never tntered empty rows. Then where have these empty rows come from? Any idea? stored as spank’) \r be sa tin was appeal with EOL charac “8 ['shradha", *4500", *23°]\r on Window OS bau of EOL ratlion \a [-Nishehay', "4800", °31°] \r \a ‘So what is the solution ? You are right again ©. We should have created the file with newline argument set to null string ("') so that no EOL translation could take place. this situation would not arise. Programs 5.23 es AL What ae text files 7 2 What ae binary les ? 3. What ae CSV Bles ? 4A. Mame the functions used to rend and ite in plain text fies, 5. Mame the functions used to read and ite in binary Biles. 6 Name the functions used to read and ‘ite in CSV fie. (i) Method2. To with newline argument set to the EOL character of the (OS where the esv file was created. For instance, created the csv file on a Windos reading with newline argument the EOL on Windows is stored Recall that the table 544 lists EOL characters on vanous ICRSE Sample Paper 202021] operating systems. ‘COMPUTER SCIENCE Wn yp sn ane histatins melo 2 Tite ere Leto av ag po scar ee ey royam newline = "\r\n") as fh: \ Now the le il be ed coding : (nd oftine an na sso ng” ‘Let us now treat the earlier listed problem of blank lines in between records using he listed above. For this, we shall create the file with newline argument and then we hl ny newline argument while reading as no EOL translation would have taken plac. Programs 523(0) and () are illustrating the same, ‘The above program created a file as shown above, Let us now read fom the bow "e created file. This time we need not specify the | ‘argument as no EOL ion | doing rant hasan place, Program 523) doing he jane 5 FILE HANDING pr. ‘write program tread and diply the contents of Employe sv created in the previous progres | rtesy gem PO Te) 28 fh —— Sn er ne ome van teen oad with open("Employee.csv" Sm ki in en he mod nee how foe nl With this we have come to the end ofthis chapter. DATA FILES IN PYTHON nt Pi Progress In Python 5.1 “This PiP session aims at giving you practical exposure to file handling in Python. ) flanction suze o open a dat flea program dough afleabjet oro file-hondle) + A filesmode governs the ope of operations (eread/ write / append) posible inthe opened file. refers © While read) reads some byes fom te file ond retas i a orig, readline ) reads @ ie ot atime ard odlines() reads ol the lines from the fle and eu iti the frm of st. COMPUTER SCIENCE WH votes erro a cy el oh 0) 7 eel de pian l een om este fle pre ecedein Cn ee emer feo nee Soon a apne vow ooo cos sce ama eye « Roopemncnhigan tase etnias Foe oh aaj ects nde ta ae Tenge crate Con ene nme es EL eatin sure object which converts the user dat ina OTOs iy MULTIPLE CHOICE QUESTIONS Information stored ona storage device with a specific name i called 3 (@) array tionary {file (@ tuple 2. Which ofthe following format of files canbe created programmatically through Python tag files (€) Video files —_(@) Binary files | (file « open (@ ile « opentfie = seit", “Ww") wt pope FRE HANDING 4. which ofthe following option is the cont Uharacters ofa text file “Notes” ? Python statement to wead and display the first 10 (CRE Paper 223 Cem 1) 11. Which function i used to read al the charac ( ewadcharacers) (6) readal() 4) eadline() (0) readline) 13, Which function i used to write ll the charac 4a) write) (0 writecharacters) (9 writeal() 14 Which function i used to write alist of tings ina ile? (0 writechar() (@ weiteline( ) (6) writelines{)__(e)writestatement{ ) (4) writefulline) 15. Which ofthe following ts mode ofboth writing and reading in binary format in Ble? bt (Owe (owe 6. of the following isnot a valid mode to open a file? (oa 0) rw or wr 17. Which ofthe following mode in fle opening statement results or generates an error ifthe fle does (@ When you open a fie for writ (@) When you open a ile for writing if the le exists the existing fil is overwriten withthe new fe M 22. Which ofthe following functions o ‘COMPUTER SCIENCE WITH Prt, a the poston file pointer and retums It new px Gai) @) ten (ofeset) toy (pq, (3 tain the binary format? (@ send) (ofa fle object? {CBSE Peper 21 Gam 26. Which ofthe following statement is incorrect in the context of pickled binary files 7 {@) The cso module is used for reading and writing objects in binary files, rc) ‘The load ) of the pickle module is used to read objects. (@ The dump) of the pickle module is used to write objects 127. What isthe significance ofthe seek) method ? ( socks the absolute path ofthe file. (©) The pickle module is used for reading and writing objects in binary files {CBSE Paper 202 em {USE Pape 200 (en (b) I tells the current byte postion of the file pointer within the file, a) ® « File_object.seek(oFfset [, reference point]) seek(offset [, reference. pott seek(offset, File object) ter of ev files is 6 Te Lerma Ip, We ean suppress EOL translation i text file by giving ‘argument in open( )- th, The fle mode to open a binary file for reading as well writing is {9, The file mode to open a binary file for writing as well reading is, . 2b To specify 2 different delimiter while writing into a sv file, cov.writer()- TRUE/FALSE QUESTIONS 1. When you open a file for reading, ifthe fle does not exist, an error occurs. 7 7. When you open a file for writing if the file does not exist, an error occurs. £ 3, When you open a file for writing, if the ile exists, the existing file is overwritten withthe new file. 1 Assertion. Python is said to have broadly two types of files - binary and tet fle, even when there Fe CSV and TSY files also. Reason, The CSV and TSV are types of delimited text files only where the delimiters are comma And tab respectively separates the values in csv files is called the __. p- COMPUTER SCIENCE wan HANOUNG 6 rH Pr 5 rue work with text files, CSV files and = tats 12 Awertion. The ile modes °F, “w", “a” work a ‘TSV files a rte a fantom tats tha cee flere nd prs te ted text files only. lo reveal the type of file these are being Reason. The binary file modes fix with regular file modes. ‘wed wg, 4 Accenon ‘Piling she process whereby a Python object hierarchy is converted int Reason A binary file works with byte-streams. rs, 5. Accenn ‘Pking isthe process whereby a Python abject hierarchy i converte into aby (0S Paper 3205 Cer 1} "MOTE : Answers for OTQs are given at the end of the Book. — Solved Problems set started isto (© qui talking and begin doing ( a (0 The way to get started is to quit talking and begin doing (@ gniod nigeb dna gniklattiug ot si detratsteg to yaw ehT fhread 2 wil rea the entite le content and place the file pointer atthe the fureadts),it will return nothing as there ae no bytes to be read from EOF thus

You might also like