You are on page 1of 34
File Handling ee. Chart er 5.1 Introduction 52. Data Files 53. Opening and Closing Files 54 Reading and Writing Files 58. Standard Input, Output and Error Streams INTRODUCTION Most ith files, This is because files help in storing information ae a Ee smart files ; Database programs create files of pene ee files and generate executable So, we see, it is the files : ei grams. A file in itself i a bunch of bytes stored on some ee very programming language offers some provision ; jon i no exception and in this chapter, you shall r rams. is COMPUTER SCIENCE WITH, PHN ay 5.2 DATA FILES te ‘The data files are the files that store. data pertaining.to.a specific 2PPcatory Thy diafa files can be Stored in two ways = © Textfiles ©. Binary. files ene the one which is default il ion in ASCII or Unicode characters ( cE), fax for: coarse ine tatonn), In textiles, each ine of text is terminated, (delimited) with ee ita as EOL (End of Line) character. In text files, some internal translation place when this EOL character is read or written. In Python, by acta EOL characteris, newline character (’\n’) or carriage-return, newline combination (‘\r\n’). 2. Binary Files F 3 oe files just file that contains information inthe same formatin which the informa is held in memory, iy the ile content that is returned to you is raw (with no translation or ny specific encoding). In binary fie, there is no delimiter for a line. Also no translations occur binary files. As a result, binary files are faster and easier for a program to read and write than are text files. As long as the file doesn’t need to be read by people or need to be ported to 4 different type of system, binary files are the best way to store program information, 5.3 OPENING AND CLOSING FILES In order to work with a file from within a Python program, you need to open it in a specific mode as per the file manipulation task you want to perform. The most basic file ‘manipulation tasks include adding, modifying or deleting data in a file, which in turn include any one or combination of the following operations : ® reading data from files © writing data to files © appending data to files Python provides built-in functions to Perform each of these tasks. But before you can perform these functions on a file, you need to first open the file, 5.3.1 Opening Files = In data file handling through Python, the first thing that you do is open the file. Itis done using __open() function as per one of the followi syntaxes ; = pen() = open(, ) = open("taxes. txt") <—— Pion wil lok fr this fle in cument Pang working directory file “taxes, ‘tin file mode as read mode (de‘ault mode) and attache 5: FILE HANDLING (all Consider one more file-open statement « a File3 = open(“e:\\main\\resuit txts “wy <——— Potton wit ook fortis file : jn Elman foe The above statement opens file “resul 4 E\main) in write mode (because of "art, 10rd in folder attaches it o file object namely files, "BY" 48 Mode) and Tl (Notice that in above file open Statement, the fi “ A file-object is also known as double slashes in place of single slashes) Path contains Mechande i entencrstionaiaaamm! The above given three file-open statements . must have raised se oa ( What is file-object ? (i) What is mode or a. questions in your mind : The coming lines will have answers to all your quest; for now, let us summarize the file open( )toncge on Ot ) function. BTR al © Python’s opent ) function creates ale object which serves as.a link to a file residing on your computer. file in readmode, the given file must © The first parameter for the open( ) function is a path to xistin the folder, otherwise Python the file you'd like to open. If just the file name is given, Mills FlleNotFounderror, then Python searches for the file in the current folder, Please note that when you open a © The second parameter of the open function corresp (1), write (‘w’), or append (‘a in read (‘x’) mode. onds to a mode which is typically read ‘). Ifno second parameter is given, then by default it opens it Fe ci a Sas woe | Figure 5.1 summarizes the open( )function of Python for you. | | | As you can see in Fig. 5.1, the slashes in the path are ‘open(“c:\\temp\\data. txt”, 'r’) doubled. This is because the slashes have special meaning and to suppress that special meaning escape Figure 5.1 Working of file open( ) function. sequence for slash i.e., \\ is given. However, if you want to write with single slash, you may write in raw string as : atom ti (aaa at f=open(r"c :\temp\data.txt’, "r") poretetes The prefix r in front of a string The prefix ri of a string makes it raw string that means makes jt raw string that means there is espe pest attached to any character. there is no special meaning mele atin ight give you incorrect attached to any character. following statement might gi 198 an reg. f= open(r"c:\temp\data. txt", 5.3.1A File Object/File Handle File objects are used to read and write dat ‘The file object is used to obtain a reference to and open it for a number of different tasks. File object (also called file-handle) is very important and ay : tool as through a file-object only, a Python program can work avaiable fora number stored on hardware. All the functions that you different tasks, ~—-———"_? perform on a data file are performed through file-objects. pent ), Python stores the reference of mentioned file in the file-object, 4 with fil When you use COMPUTER SCIENCE WITH Prt, a i th (ii) Give raw string by prefixing the file-path string w! am you just ve the fe name its path (2.9, just “data,eqe than “c |\terp\\data ee 1 rnc, {he sae will open/create the file in rectory in which the module stored. ay Aflle objectisa reference oa On isk. It opens and makers ") a to a file on disk. the file on disk file-object of Python isa stream of bytes where the data can be read either byte by byte or line by line or collectively. All this will be clear to you in the coming lines (under topic - File acess modes), 5.3.1B File Access Modes When Python opens a file, it needs to know the file-mode in which the file is being opened, A file-mode governs the type of operations (such as read or write or append) possible in the opened file i, it refers to how the file will be used once it’s opened, File modes supported by Python are being given in Table 5.1 Table 5.1 File-modes Text File | Binary File a | Ma | en vee v ‘tb’ __| read only * File must exist already, otherwise Python raises I/O error. “we ‘wb’ | write only * If the file does not exist, file is created. * If the file exists, Python will truncate existing data and over- write in the file. So this mode must be used with caution. al ‘ab’ append * File is in write only mode. * If the file exists, the data in the file is retained and new ; data being written will be appended to the end. oo + If the file does not exist, Python will create a new fie. MP or | read and write | File must exist otherwise error is raised. % Both reading and writing operations can take place. * File is created if does not exist. * If file exists, file is truncated (past data is lost). * Both re. and writing operations can take © File is created if does not exist. || # IE file exists, file’s existing data is retained ; new data * i a 5 FILE HANDLING fo create a file, you need to o node that supports writemode ew ce? i fi! or ‘av’ modes). W", or ‘a! of rea tt write/append) possible in 432 Closing Files Scio how the Mev be tan oe eee BP cats ie a the close() m, fil vethod of it rt Screg saan tte nye a les explicitly, fam but: it is good ractice to i data out to the file until itis closed (hig a Tee, the operating system may not weite the program exits unexpectedly there Performance). What this means is that if the written to the file! So the moral is : once you finish wane eos ata may not have bee The close( ) function accomplishes this task and it een oe following general form ; takes the a .close( ) oo -close( ) function breaks the link of For instance, if a file Master.txt is o ' fle-object and the file on the disk inst rtxt is opened via file- autfite, it may be closed by the following statements” Met, Sosel tasks can be is a danger that outfile.close( ) <—— The close() must be used =~ te See! Please remember, open( ) is a built-in function (used standalone) while close() is a method used . with file-handle object. 54 READING AND WRITING FILES Python provides many functions for reading and writing the open files. In this section, we are going to explore these functions. Most common file reading and writing functions are being discussed in coming lines. 54.1 Reading from Files Python provides mainly three types of read functions to read from a data file. But before you can read fen a file, the file must be opened and linked via a file-object or file handle. Most common file reading functions of Python are listed below in Table 5.2. Tebles.2 Python data files — reading writing functions (Si Description ; : reads at most m bytes; if no 1 is specified, reads the entire file. ¢ Returns the read bytes in the form of a string. In [28]: filed = open("E:\\eydata\\info. exe") ‘.readline([n]) reads a line of input ; if m is specifieg ‘most 1 bytes. toads at Returns the read bytes in the form of g 4p. ending with In(line) character or retums 4 Hid string if no more bytes are left for reading in file. the Jn [20]: fled = open("E:\\mydata\ Info.) In [21]: readinfo = filet.readiing() In [22]: print(readInfo) Ts tine to wore with Fes. (Tinea) readlines() | .readlines() In [23]: Filed ~ open("E:\\mydata\\info.tet*) In [24]: readinfo ~ filet.readlines() 1m [25]: print(readirfo) ["It's tine to work with Files.\n", ‘Files offer an ease and power to sti for later use.\n", *: store(write) in it and reed frou it.\n'] In [26]: type(readinfo) Out[26]: list reads alll ines and returns them in a list your work/data/Information ly create a file and ", ‘Or open an existing file Read into list type fdllehandle> in above syntaxes is the file-object holding open file's reference. Let us consider some examples now. For the examples and explanations below, file namely poem.txt storing the content shown in Fig. 5.2. WHY 2 we are using a We stil give our best. We have to steal, _ We don't get luxury, fe don't get childhood, We work, we try to be better We work with full zest ‘But, why is that we just don't know any letter. But, why is that we stil don't get a meal a Reading a file's first 39 bytes and Printing i ted = ~—* tyFile = open(re. \poem. txt’, “ey ‘ str =myfile, ie ; E -Pead( 36 ) —_ t e Petia af peor print(str) we specify number of bytes with readi i from the file. The next read( ) will start ae 2 mer pee eat aad '§ onwards from the last position read. Code The output produced by above code is : WHY? we work, we try é Ifneed to perform just a single task with the open file, then you may combine the two steps of opening the file and performing the task, eg, following statement Fit fmcion il pen the fle andthe second >>> File(rE : \poem.txt’, "r").read(38) “finn ml pore with he tat of fe function, i.e., the reference of open file would give the same result as that of above code. For example, the following code will return the first line of file poem.txt : open("poem.txt", "r").readline() Code Snippet 2 Reading n bytes and then reading some more bytes from the last position read myfile = open(r'E:\poem.txt’, '"’) = str =myfile.read( 38) print(str) amelie str2 = myfile.read( 5@)<——_ print(str2) myfile.close() The output produced by above code is : en) EE prin as entered newline afer ‘output ie here EAT Bi OK, 202 — : by print statement in the : ters inserted by om ewline charat foment s0 that print does not put any agit on t want to have the n . poe argument in the end of print ‘de snippets 3 and 4 below. ton to newline characters in the output. Refer Code Snippet 3 Reading a file’s entire content ey myfile = open(r’é :\poem.txt', str =myfile.read() «5. ten re Aon print(str) argument, | myfile.close() The output produced by above code is : WHY? We work, we try to be better We work with full zest But, why is that we just don’t know any letter. We still give our best. | We have to steal, i But, why is that we stil] don’t get a meal. We don’t get Tuxury, i We don’t get childhood, i But we sti11 work, Not for us, but for all the others. why is it that some kids wear shoes, BUT we make them ? by Mythili, class 5 Sods Snippet 4 — Reading a file's frst three lines ~ line by line mfile = open(r'E:\poen.txt', "ny str =myfile.readline() Print(str, end =' *) str=nyfile.readline() Print (str, end Argument end = *? ai the end of print) statement str= myfile.readline() will ensure that Output shows exact content of the \ print(str, end=* +) datafile and no print-iaserted newline character a? myfile, close() The readline( ) function ill ine i: * ercouiee inthe daa fe" lin. tine is considered tl anewtine racer 00 The output produced by above code is : WHY? <———— Line 1 Lite 2 We work, we try to be better <——— = open(]) aoe COMPUTER SCIENCE WITH Poy ~My the By is ine ofa file is by line where a line o| one x ible ves through the file line ee, eerie ic to and including a special character called the oa character (iy a the for loop’s variable starts with first line and with each aa ey a ca neXtlng the for loop iterates through each line of the file the loop variable wi! © CUTTER Lng the file as a string of characters. Code Snippet 6 Displaying the size of a file after removing EOL characters, leading and trailing white spaces and blank lines myfile = open(r€:\poem.txt’, "r") stri #initially storing a space (any non-None value) size | tsize=0 | while stri : str =myfile.readline() tsize = tsize + len(str1) | ] size = size + len(stri.strip()) print ("Size of file after removing all EOL characters & blank lines:", size) print("The TOTAL size of the file:", tsize) myfile.close() The output produced by the above code fragment is : Size of file after removing all EOL characters & blank lines : 360 The TOTAL size of the file : 387 Alll the above code fragments read the contents from file in a string. However, if you use eadlines( ) (notice ’s'in the end of the function), then the contents are read in a List. Go through Next code fragment. Snippet 7 Reading the complete file-in a list myfile = open(r'E:\poem. txt’, Ss to steal, \n' why “we don’t get luxury, 11 work,\n', ‘Not for wn gl Write a program to display the size of, file j in myfile = open(rE:\poem.txt!, pe wu are familiar with Now that you these Teading fun, \ctions’ working, let us write some programs, bytes, str =myfile.read() , ‘ ae en(str) a romtaieronary emir dp 5.2 Write a program to display the number of lines in the file p. myfile = open(rE:\poem.txt', "py er s=myfile.readlines() linecount = len(s) print("Number of lines in poem.txt is" myfile.close() $42 Writing onto Files After working with file-reading functions, let us available in Python. (See Table 5.3). Like reading open files, ie, the files that are opened and linked via a file-object or ‘Tae53° Python Data Files ~ Writing Functions linecount) Number of lines in poem.txt is 18 talk about the writing functions for data files ions, the writing functions also work on file-handle. Syntax Description .write(str1) writes string str] to file referenced by .writelines(L) for an file. That means, Gnto the file while file opened in can also 4 mode, Python Oe tt ce wih the writes all strings in list L as lines to file refe- renced by rites an existing file or creates a he same name, the earlier data gets lost. pauper ins its previous (+) with file read mode to ‘mode eeicatarabsl a COMPUTER SCIENCE WITH Pytiay “a (ii) to create a new file or to write on an content, ee (@) if the file has been opened in write-only mode (“w”) i (0) if the file has been open in ‘w+’ mode to facilitate writing as well as read; (i) Make sure to use close( ) function on file-object after you have finished writing " sometimes, the content remains in memory buffer and to force-write the content gy and closing the link of file-handle from file, close( ) is used. existing file after truncating/ overwriting ig a Let us consider some examples now. Code Snippet 8 Create a file to hold some data ) fileout = open("Student. dat” for i inrange(5) : name = input(“Enter name of student. Fileout.write(nane) 5. leout, The write() will simply write the content in 4 ee ae rs uithout adding any extra character Hts important to use close() The sample run of above code is as shown below : >>> Enter name of student :; Riya Enter name of student : Rehan Enter name of student : Ronaq Enter name of student : Robert Enter name of student : Ravneet Now you can see the file created in the same folder where this Python script/program is saved (see Fig. 5.3(a) below). However, if you want to create the file in specific folder then you must specify the file-path as per the guidelines discussed earlier. Also, you can open the created file (“student.dat” in above case) in Notepad to see its conten, Fig, 53(#) shows the contents of file cteated through code snippet 5. The data you entered is part of the fle. EUT notice that write does rot add a newline character on its xt “at look at Fig. 5.3(b) fully 8: 5.3(b) that i Grrr from the file-contents. gner°iN8 con : 207 olg jine character('\n’) after every re dd ing in file» line Wise, make sure Mepicted in code snippet 9. ; as gnippet 9 Create A file L0 old some dat file a (This code is creati NG a different file th, Fileout = open(" an created with code sni PEN("Student1 txt", myn Snippet 8) for i inrange(s) ; a) fame = input ("Enter n; lame of Fileout.write(naney ent fileout .write(\n') +—— The newline char Wnt fileout .close() arate ‘Wn’ writen afer exer name The sampk i bel PI mi ofthe above code is as shown Sieh >>> Saag aren aie Enter name of student : jaya ond of every name as Enter name of student : Jivin you added a newline Enter name of student : Jonathan after every name Enter name of student : jagjeet Enter name of student : Javed The file created by code snippet 9 is shown above. sd (ode snippet 10 Creating a file with some names separated by newline characters without using write( ) st bs Ta cel ‘i function. : (For this, we shall use writelines(,) inplace of write() function which writs the content of 1 list to a file. Function wrtelines) also, does not add newline character, s you have take care of adding newlines to your file.) fileout = open("Student3. txt", “w") List1=[] for i in range(5) : name = input ("Enter name of stl Responsibility 19 add newline Nn List append(name +'\"') acter if ogra’ fileout .writelines (List?) _ fileout.close() ee above code iss shown below: Sample runo! >> enter name enter aren enter name enter name oo 7. vor —, ON yy 3 g, let us write some iting functions’ working, Me pry Now that you are familiar with these writing = based on the same. ie rll umber, ames and marks ofthe toes OF 8 IAS ram yy Write a program to get roll numbers, P 5.3 a i store these details in a file called “Marks.det Se there in the class?" ae count = int (input("How many students are Fileout = open ("Marks det’ for i in range(count) : o ahiso - print("Enter details for student", (i+1), "below:") rollno = int (input ("Rollno: ))" name = input ("Name :") marks = float (input ("Marks:")) ae ","+name+","+ str(marks) #\n rec = str(rollno) +", speaitomtes(ees) ‘adding commas in Berson fileout.close() How many students are there in the class? 3 Enter details for student 1 below : Rolino : 12 Name : Hazel Marks : 67.75 Enter details for student 2 below : RolIno : 15 Name : Jiya Marks : 78.5 Enter details for student 3 below : | Rolino : 16 Name : Noor © Marks : 68.9 If you carefully notice, we have created comma separated values in one student record while writing in file. So we can say that the file created by program 5.4 is in CSV (comma separated values) format or itis a delimited file where comme fe the delimiter, I] J 2-4 Write a program to add two more students while s 2 estr 12,Hazel 67.75 str = Fileinp.readiine() aac print(str) eee 17, akshar,78.9 fileinp.close() 23, Jivin,89.5 5.4.3 The flush( ) Function When you write onto a file using any of the write functions, Python holds everything to write in the file in buffer and pushes it onto actual file ren noraBe device a later time. If however, you ‘Want fo force Python to write the contents of butfer ont, storage, you can use flush) function, syntax to use flush( ) function is : . flush() Consider the following example code : F = open( ‘out. 1og, ws") F.write( ‘The output is \n’) F.write( "My" + "work-status "4" is") rite 20 far, With his statement, the svngs F-ALUsh() $n i cla a workestaua hhave been pushed on to actual file on disk. The flush( ) function forces the writing of data on disc still pending in output buffer. S='OK.' F.write(s) | F.write("\n') | Sy Mee write sates’ sins my tt | be pending to be writen onto disk # some other work f.write( ‘Finally Over\n') } f-flush() —_—_—— The flush( ) function ensures that whatever is held in F.close() Output buffer, is writen on tothe actual file om disk 5.4.4 Removing Whitespaces after Reading from File in i i from file and return it in stri 1d id readline() functions discussed above, read data f fi tin aes béadlinas( ) function returns the entire file content ina list where each line is one item of the list. COMPUTER SCIENCE WITH PYTHON ~ yy the leading and trailing whitespaces i.e, spaces or tabs op move any of these trailing and leading whitespaces, yoy and strip( )] as shown below. All these read functions also read newline characters. If you want to rer can use strip() functions [rstrip( ), Istrip() Recall that © the strip() saa iven character from tr © the rstrip( ) removes the given ¢ Ef © the Isrip( ) removes the given character from leading end ive, left end. To understand this, consider the following examples : 1. Removing EOL “n’ character from the line read fh=file("poen.txt, "r") Witt remove the end of line ne removes the given character from both ends. ailing end i.,, rigit end. from the file. ine character “\n Line = fh. readLine() >>> fh = FileC'e :\\poem. txt! Line = Line.rstrip(\n) >>> Vine = fh.readTineQ) 2. Removing the leading whilespaces from ce Ten(line) the line read from the file Line = file("poem.txt, "r").readline() >>> line2 = line.rstrip("\n') Line = line.1strip() >>> Ten(1ine2) 13 Now can you justify the output of following code that works with first line of file poemtext. >>> 1ine3 = line.stripO shown above where first line containing leading >>> ‘Ten(1ine3) 8 spaces followed by word ‘WHY? anda‘\n’ in 4 the end of line. Info Box 5.1 $s ieee | Following lines list the steps that need to be followed in the order as mentioned below. The five steps to use files in your Python program are : 1. Determine the type of file usage Under this step, you need to determine whether you need to open the file for reading purpose (input type of Usage) or writing purpose (output type of usage). Ifthe data is to be brought in from a file to memory, then the file must be opened in a mode that supports reading such as “r” or “r+” etc. Similarly, if the data (after some processing) is to be sent from memory to file, the file must be opened in a ‘mode that supports writing such as “w” or “w+” or “a” etc 2. Open the file and assign its reference to a file-object or file-handle Next, you need to open the file using open( ) and assign i i i ign itto a file-handle on which all the file-operations will be performed. Just remember to open the file inthe file-mode that you decided in step 1. a 3. Now process os required re oa LOE ‘You need to write instructions to process the file as desired. For example, you mightneed and then read it one line ata time while making some computation, and s0 on. 4. Close the file Chopter § : FILE HANDLING 5.4.5 Significance of File Pointer in File Ho r pone Mites Lee which tells the current Position in the file where writing or - Place. (A file pointer in this context wari like a Goa MER ENG book). jenever you read something from the f : Presieine tie pointer ig \e file or write onto a file, then these two things happen (this operation takes pl ndling ( lace at the position of file-pointer and To 208 (i) file-pointer advances by the specified number of bytes | ee inaction Figure 5.5 illustrates this process. Itis important to understand how a file pointer works in Python files. The working of file-pointer has been described in Fig. 5.5. 4. fh=open("Marks.det, "rn" A Dab a Alea [els el position of file-pointer when file is opened in read mode (‘r), Le, »file-pointer les in beginning 2, ch=fh.read(1) will read 1 byte from the file from the position the file-pointer is currently at: and the file pointer advances by one byte. That is, now the ch will hold ‘1" and the file pointer will be at next byte holding value 2” (see below) fel Ts: “Ebel ‘See now, the file-pointer has advanced by 1 postion as previous read operation read 1 bye only Now the next read will take place at the current postion of file-pointer. Tou eleleea 3. str=fh.read(2) will read 2 bytes from the fle from the position the fle-pointer is currently at and the fle pointer advances by 2 bytes. That is, now the str will hold ‘2’, and the file pointer will be at next byte holding value’H’ (see below) Ee ae ‘See now, the file-pointer has advanced by 2 positions as previous read operation read 2 bytes only, Now the next read will take place at the current position of file-pointer. Talal ie wlll Figure 5.5. Working of a file-pointer. 5.4.54 File Modes and the Opening Position of File-Pointer The position of a file-pointer is governed by the filemode itis opened in. Following table lists the opening position of a file-pointer as per filemode. Table 5.4 File modes and opening position of file-pointer File Modes | 1, tb, rt, tht, r+b. beginning of the. - - - - w, wb, wt, wht, wtb beginning of the file (Overwrites the file if the file exists). a, ab, at, abt, atb [at the end of the fle if the file exists otherwise creates a new file. Pine COMPUTER SCIENCE WITH PYTHON, 5.5 STANDARD INPUT, OUTPUT AND ERROR STREAMS ive input to a program interactively or by typing, you know ae pet Es ere Beard: ‘Silay, if someone says that the output is to be displayed, you know which device it will be displayed on ~ the monitor. So, we can that the Keyboard is the standard input device and the monitor is standard output device, Similarly, any error if occurs is also displayed on the monitor. So, the monitor is also standard error device. That is, © standard input device (stdin) — reads from the keyboard © standard output device (stdout) — prints to the display and can be redirected as standard input. © standard error device (stderr) — Same as stdout but normally only for errors. Having error output separately allows the user to divert regular output to a file and still be able to read error messages. Do you know internally how these devices are implemented in Python? These standard devices are implemented as files called standard streams. In Python, you can use these standard stream files by using sys module. After importing, you can use these standard streams (stdin, stdout and stderr) in the same way as you use other files. Interesting : Standard Input, Output Devices as Files If you import sys module in your program then, sys.stdin.read( ) would let you read from keyboard. This is because the keyboard is the standard input device linked to sys.stdin. Similarly, sys.stdout.write( ) would let you write on the standard output device, the monitor. sys.stdin and sys.stdout are standard input and standard output devices respectively, treated as files. Thus sys.stdin and sys.stdout are like files which are opened by the Python when you start Python. The sys.stdin is always opened in read mode and sys.stdout is always opened in write mode. Following code fragment shows you interesting use of these. It prints the contents of a file on monitor without using print statement : import sys Thee satemens wou 7 OPEN(P"E: \poem. txt") urite on flefdevice Line1 = fh.readline() ascciated with gsstdou, . 1ine2 = fh.readli ite vith esto, | Line? = fh.readline() sys. stdout .write(1ine1) Pp sys. stdout write(1ine2) sys.stderr.write("No errors occurred\n") Info Box 5.2 MTT *)-) Bae Chapter 5 FILE HANDLING CUI aren Y { execute as a pair, syntax for using with statement is : with open(, ) as ; on statements» The classic example is opening a file, , ) For instance, if you have a file open in handle flel and you want to write alist namely list in the file, then ‘you may write : Pickle.dump(1ist1, file1) In the same way, you may write dictionaries, class objects etc. in binary file, For instance, to write an object student of class type Student in a file open in handle file2, you may write : pickle.dump(student1, file2) Consider program 1 that is doing just the same. Program 1. Program to write instances of class Student onto a file namely student.log, import pickle class Student : def _init__ (self, rno=, name self.rol1No = rno def display(self) : print("Student details are:") print("Roll number :", self.rol1No) print(‘Nane :", self.name) print ("Marks in 3 subjects :", self.marks1. self.marks2, self.marks3) studi = Student( 13, "Rohan") # object created stud2 = Student (15, "Nitya") # object2 created stud1.readMarks() stud2.readMarks() filel = open ("student1. log”, “wb") pickle.dump(stud1, file1) Sa These hwo statements would write instances of. pickle. dump(stud2, ile1) Student type to file associated with handle filet file1.close() ‘The output produced by above code is : >> Enter marks of 3 subjects Subject1: 73 Subject2: 75 Subject3: 80 Enter marks of 3 subjects Subjectl: 84 Subject2: 79 Subject3: 77 And if you open the file student.log, youll see some special Characters in the created file — added by pickling process, (Gee the file shown on the right) hope 5 PLE HANDLING : th (Following program 2 does the same for you, It reads the objects written by 2 from the file student.log and displays them. But before you move onto the program code, it f eee mt to know that pickle.load( ) function would raise EOF “rror when you reach end-of-file while reading from the file. fl Thus, you must write pickdle.load( ) enclosed in "ty and except statements as shown below, = open (, ) try: = pickle-Joad() «— Pile lot s writen benveen # other processing statements ee except EOFError e .close¢) *— “ine he fle here ‘You may also use the with statement to open your fie, Program 2. Program to read instances of class Student from a file namely student.log. import pickle class Student : def init__(self, rno=0, name self .rol1No = rno self.name = name self.marks1, self.marks2, self.marks3 = 0, 0,0 def readMarks(self): print "Enter marks of 3 subjects" self.marks1 = float (input ("Subject1: )) self.marks. ‘loat (input ("Subject2:' self.marks3 = ‘loat (input (“subject: def display(self) : print("Student details are:") print ("Roll number :", self.rol1No) print ("Name :", self.name) print ("Marks in 3 subjects :", self.marks1, self.marks2, self.marks3) studi = Student() = be 1. s ") Read ly: when no more filel = open ("student1.1og" ) ies a try: acral eras exci 1s returning the same data as Wille True 2 4 ee es fe 218 \/p DATA FILES IN PYTHON Progress In Python ete ai Cs iP cae ‘This PriP session aims at giving you practical exposure to file handling in Python. nce wil Fill it in PriP 5.1 under Chapter 5 of practical component-book ~ Progress % a Comp: Python after practically doing it on the computer. Let Us REVISE % Afile in itself is a bunch of bytes stored on some storage devices like hard-disk, thumb-drive etc, % The data files can be stored in two ways : (i) Text files (ii) Binary files. A text file stores information in ASCII or Unicode characters, where each line of ext is terminated, (delimited) with ‘aspecial character known as EOL (End of Line) character. In text files some internal translations take place when this EOL character is read or written. % Abinary file is just file chat contains information in the same format in which the information is held in memory, ice, the file content that is returned to you is raw (with no translation or no specific encoding). The open( ) function is used to open a data file in a program through a file-object (or a file-handle). A file-mode governs the type of operations (e.g, read / write / append) possible in the opened file i.., it refers to how the file will be used once it’s opened: A text file can be opened in these file modes : ‘r’ , ‘w’, ‘a’, r+”, ‘wt?, ‘at? A binary file can be opened in these file modes : ‘rb’ , ‘wb’, ‘ab’, ‘r+b" (‘rb+"), ‘w+b'(‘wb+’), ‘a+b'(‘ab+), The three file reading functions of Python are : read{ ), readline( ), readlines( ) While read{ ) reads some bytes from the file and returns it as a string, readline( ) reads a line at a time and readlines( ) reads all the lines from the file and returns it in the form of a list. The two writing functions for Python data files are write( ) and writelines( ). While write( ) writes a string in file, writelines( ) writes a list in a file. The input and output devices are implemented as files, also called standard streams. There are three standard streams : stdin (standard input), stdout (standard output) and stderr (standard error) The absolute paths are from the topmost level of the directory structure. The relative paths are relative to current working directory denoted as a dot(.) while its parent directory is denoted with two dots) ee re ee PRE Re [a 0.1. Ss 4 Multiple Choice Questions = Sea, Chapter 5 3 10, ul 12, 13. 14, 15, FILE HANDLING To.open a file c\se.txt for appending data, we fie (a) file = open(“e:\ \ss.txe, “qn (0 file = open(rc coe (a a eel, ind a") (@) file = open(file = “c:\ss.txt", “w") To read the next line of the file fro ve eee 'e file from a file object infi, we (a) infi.read(all ee O infi eee ume ee eel ) (4) infi.readlines( ) Jo read the remaining lines of the file from a file object infi, we use (© file = openifile = “e:\ \ss.tut", “wry () file (a) infi.read(all) () infiread ) (0) infi.readline( ) (@) infi.readtines( ) The readlines( ) method returns (a) str (®) a list of lines (c) a list of single characters (@) alist of integers Which of the following mode will refer to binary data ? (a)r () w (+ (@>b In file handling, what does this term means “r, a’? (@) read, append (©) append, read (6 all of the mentioned (@ none of these Which function is used to read all the characters 2 (a) read( ) () readcharacters( ) (0) readall ) (@ readchar( ) Which function is used to read single line from file ? ( readiines( ) (a) readline( ) (@ readfullline( ) (0) readstatement( ) Which function is used to write all the characters ? (® writecharacters( ) (a) write( ) (@) writechar( ) (©) writeall( ) Which function is used to write a list of strings in a file 2 (b) writelines( ) (a) writeline( ) (@) writefullline( ) (0) writestatement( ) Which of the following is modes of both writing and reading in binary format in file.? (4) wht Ow (©) wb (@ we Which of the following is not a valid mode to open a file ? (a) ab () rw (or @ wt What is the difference between r+ and w+ modes ? (a) No difference. a ‘ (b) In r+ mode, the pointer is initially placed at the beginning of the file and for w+, the pointer is laced at the end. : aces © In are mode, the pointer is inialy placed atthe beginning ofthe ile and for rth pointer is placed at the end. (d) Depends on the operating system. COMPUTER SCIENCE WITH PYTHON _y Fill in the Blanks . The default file-open mode is mode. A governs the type of operations (e.g., read/write/append) possible in the opened file, files. The other name for file object is . The ____file mode will open a file for read and write purpose. 6. The ____ file mode will open a file for write and read purpose. 7. To close an open file, _ method is used. 8. To read all the file contents in form of a list, _ method is used. 9. To write a list in a file, method may be used. 10. To force Python to write the contents of file buffer on to storage file, _ method may be used, ff 2. 3. The two types of data files can be __ files and 4. e True/False Questions 1, When you open a file for reading, if the file does not exist, an error occurs. 2. 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 file exists, the existing file is overwritten with the new file, 4, The absolute paths are from the topmost level of the directory structure. 5. The relative paths are relative to current working directory. 6. The relative path for a file always remains same even after changing the directory. 7. The types of operations that can be carried out on a file depend upon the file mode a file is opened in. 8. Ifno path is given with a file name in the file open( ), then the file must exist in current directory. 9. Functions readline( ) and readlines( ) are essentially the same. 10. Python automatically flushes the file buffers before closing a file with close( ) function. 2 jiven at the end of the book. i is the difference between read ) and readlines( ) function? read() reads from a file in read mode, and stores its contents in a string type variable. () function, reads from a file in read mode and returns a list of al lines in the file: case D 20151 file in read mode and returns the next ine in he fle returned data is of string type) [mode and returns alist ofa Iinesin the file Write a single loop to display all ihe whitespaces contents of a text file © :\poom.tet after removing leading and trailing Solution. «for line én fi1e(“poem txt") Print(line.strip()) Write a function stats( ) that accepts a filename Solution. def stats(filename) : longest for line in file(filename) Af len(1ine) > len(longest) : longest = line print("Longest Line’s length print (longest) 4nd reports the file's longest line, Len(longest)) What is the output of following code fragment ? Explain out = file(“output..txt" out.write("Hello, world! \n") out.write("How are you?") out.close() file(“output.txt") .read() Solution. The output will be ‘Hello, world!\nHow are you?" The first line of the code is opening the file in write mode ; the next two lines write text to the file, The last line opens the file and from that reference reads the file-content. Function file( ) does the same as that of open( ). Thus file(“output txt”) will give the reference to open file, on which read{) is applied. Write a function remove_lowercase( ) that accepts two filenames, and copies all lines that do not start with a lowercase letter from the first file into the second. Solution. def remove_lowercase(infile, outfile) : output = file(outfile, "w" for line in file(infile) : if not line[9] in "abcdefghijklmnopqrstuvwxy2” : output .write(1ine) output.close() What is the output of following code ? file("e:\\poem.txt", "r"). readline().split() Recall that poem.txt has some leading and trailing whitespaces. Solution. [wHy?) What is the output of following code ? file(’ \\poem.txt", ark -readline() Solution. "WHY? \n" a COMPUTER SCIENCE WITH PYTHON ay 10. u What is the output of following code ? fh = file(“poem.txt", "r") size = len(fh.read()) |. print (fh.read(5)) Solution. No output Explanation. The fh.read{ ) of line 2 will read the entire file content and place the file pointer at eng of file. For the fh.read\6), it will return nothing as there are no bytes to be read from EOF thus print) statement prints nothing. Write a program to display all the records in a file along with linelrecord number. Solution. h = open("Result.det", "r") count = @ rec="" while True : rec = fh.readline() if rec break count = count +1 print(count, rec, end = '') # to suppress extra newline by print h.close() 12. What is the output produced by following code ? ‘obj = open("New.txt","w") obj.write("A poem by Paramhansa Yogananda) " obj.write("Better than Heaven or Arcadia") obj-write("I love thee, O my India!") obj.write("And thy love I shall give") obj.write("To every brother nation that lives.") obj.close() obj1-open("New.txt","r") _ $1 = obj1.read(48) an ‘Chopter 5 : FILE HANDLING Considering the given file, what output will be produced by the following code ? obj1=open("New. txt", “F : $1 = obj1.readline() obj1.readline() obj1.readline() obj1.read(15) ~ print(s4) obj1..close() Solution. The output produced by above code is : And thy love r 14, Two identical files (p1.txt and p2.txt) were created by following two codes (care lly go through the two codes ; y following les (carefully go throug) (@) obj = open("p1.txt","w") obj.write("Better than Heaven or Arcadia obj.write("I love thee, 0 my India!") obj.write("And thy love I shall give") obj.write("To every brother nation that lives ae obj.close( ) (®) obj = open("p2.txt", "w") obj.write("Better than Heaven or Arcadia\n") obj.write("I love thee, 0 my India!\n") obj.write("And thy love I shall give\n") obj.write("To every brother nation that lives. \n") obj.close( ) What would be the output produced if the files are read and printed with following code. a Solution. The output produced by code (a) will be : se Better than Heaven or Arcadia love thee, 0 my India!And thy love T shall giveTo every brother nation that lives. The output produced by code (b) will be : ‘A poem by Paramhansa Yogananda ste Better than Heaven or Arcadia saeepitigh I love thee, 0 my India! ‘and thy love I shall give To every brother nation that lives. —_ COMPUTER SCIEI (0) 0bj1 = open("p2.txt","r") $1 = obj1.readline() $2 = obj1.read(15) print(s2) obj1.close() Solution. No output or blank output will be produced by code (a). For code(}), the output produced will be : Better than Hea Consider the file p2.txt created above. Now predict the output of following code that works with p2.txt. Explain the reason behind this output. pl = open("p2.txt", "n") print (fp1.readline(20) ) s1 = fp1.readline(30) print(s1) print (fp1-readline(25)) Solution. The output produced by above code will be : A poem by Paramhansa Yogananda Better than Heaven or Arc The reason behind this output is that the first file-read line (ie., fp1readline(20)) read 20 bytes from the file pointer. As just after opening the file, the file-pointer is at the beginning of the file, the 20 bytes are read from the beginning of the file which retuned string as “A poem by Paramhansa\n” ~ this is because readline( ) returns the read string by adding an end-line character to it (\n). So the first line of output was printed as : Apoem by Paramhansa After the first readline( ), the file pointer was at the space following word ‘Paramhansa’, so the next readline( ) started reading from there and read 15 character or end-of the-line, whichever is earlier. So the read string was “Yogananda\n” — notice the space before word Yogananda. Hence came the second line of the output. Now the file-pointer was at the beginning of the third line and the next readline (ie fplreadline(25)) read 25 characters from this line and gave the last line of output. A text file contains alphanumeric text (say an.txt). Write a program that reads this text file and prints only the numbers or digits from the file. Solution, Chapter 5: FILE HANDLING 18. Read the code given below and answer the question : fh = open("main. txt", fh.write("Bye") fh.close() Ifthe filecontains “GOOD” before execution, what will be the contents ofthe ile after execution of this code? Solution. The file would now contain “Bye” only, because when an existing file is opened in write mode (“w"), it truncates the existing data the file. 19. Write a function in python to count the number of ines ina text file ‘STORY.TXT which is starting with an alphabet ‘A’ [CBSE Sample Paper 2019-20] Solution. def COUNTLINES(): file = open('STORY.TXT', ‘n*) file. readlines() count = @ for w in lines: print("Total lines started with ‘A’ or 'a'", count) file.close() 20. A given text file “data.txt” contains : Line 1\n \n Line 3 Line 4 \n Line 6 What would be the output of following code? fh = open (“data.txt", "r" Ist = fh.readlines() print(1st[@], end print(Ist[2], end = '* print(1st[5], en print(1st[1], end = '' print(1st[4], en print (1st[3]) Solution. Line 1 Line 3 Line 6 Line 3 Line 4 21. Write code to print just the last line of a text file “data.txt”. Solution. fin = open("data.txt", "r") LineList = fin.readlines() print("Last line =", lineList[-1]) ee a 226 22, Write a progra that copie a text fle “source txt” onto “target” barring the lines starting with a Solution. def filter(oldfile, newFile) ¢ fin = open(oldfile, "r") fout = open(newfile, "w") while True : text = fin.readline() if len(text) == 0: break if text[@] == continue fout write(text) fin.close() fout.close() filter("source.txt", “target. txt") ‘es GLOSSARY ot File ‘A bunch of bytes stored on some storage device. File mode A constant describing how a file is to be used. Stream —_A sequence of bytes. For Assignment Sclockval Sora Solutions Oza Type A : Short Answer Questions/Conceptual Questions z | 1. What is the difference between “w” and “a” modes ? a 2. What is the significance of file-object ? Sean 3. How is file open( ) function different from close( ) function ? Raed 4 . Write statements to open a binary file C:\Myfiles\ Textl.txt in read and write mode by specifying the file path in two different formats. 5. When a file is opened for output, what happens when (i) the mentioned file does not exist (ii) the mentioned file does exist ? What role is played by file modes in file operations ? Describe the various file mode constants and their meanings. 7. What are the advantages of saving data in: (i) binary form (ii) text form ? 8. When do you think text files should be preferred over binary files 2 _ 9. Write a statement in Python to perform the following operations : Chopter 5 : FILE HANDLING 2. If the file ‘poemBTH.txt’ contains the followin, (oganand) 18 Poem (by Paramhans Y : God made the Earth; a Man made confining countries And their fancy-frozen boundaries. But with unfound boundless Love J behold the borderLand of my India Expanding into the World. Hail, mother of religions, Lotus, scenic beauty, and sages! ‘Then what outputs will be produced by both the code fragments given in question1. 5. Consider the file poemBTH.txt given above (in Previous question). What output will be produced by following code fragment ? obj2 = open("poemBTH. txt", "r") $1 = obj1.readline() s2.readline(1@) $3 = obj1.read(15) print(s3 ) a print (obj1.readline()) obji.close() + Consider the file “poemBTH.txt” and predict the outputs of following code fragments if the file has been opened in filepointer filel with code: filel = open("E:\\mydata\\poenBTH. txt” (@) print("a. output 1") (@ print ("D. output 4") print(file1.read()) print(file1.readline(9) ) print() (©) print("E. Output of Readlines function is” print(file1.readlines() ) print() () print("B. output 2") print(file1.readline() ) print() (©) print("C. Output 3") print(#ile1.read(9)) print() NOTE. Consider the code fragments in succession, i., code (b) follows code (a), which means changes by code (a) remain intact. Similarly, code (c) follows (a) and (b), and so on. Whaat is following code doing ? file = open("contacts.csv", "a") name = input("Please enter name.") phno = input(“Please enter sore oe file.write(name + "," + phno + "\n" : ; : 6. Wild os oe a eran cee eee Name : Phone : COMPUTER SCIENCE WITH 8. Consider the file poemBTH.txt and predict the output of following code fragment. What exactly following code fragment doing ? . = open("poenBTH.txt", "r") nl=0 for line in f: nl +=1 print(nl) 9. If you use the code of Q.8 with pl.txt created in solved problem 14, what would be its output ? 10. Write a method in python to read the content from a text file diary.txt line by line and display the same on screen. (CBSE D 2015) 11. Write a method in python to write multiple line of text contents into a text file mylife.txtline, ICBSE D 2016) Type C : Programming Practice/Knowledge based Questions 1. Write a program that reads a text file and creates another file that is identical except that every sequence of consecutive blank spaces is replaced by a single space. 2. A file sports.dat contains information in following format : Event ~ Participant Write a function that would read contents from file sports.dat and creates a file named Atheletic.dat copying only those records from sports.dat where the event name is “Atheletics”. 3. A file contains a list of telephone numbers in the following form : Arvind 7258031 Sachin 7259197 The names contain only one word the names and telephone numbers are separated by white spaces. Write program to read a file and display its contents in two columns. 4, Write a program to count the words “to” and “the” present in a text file “Poem.txt”. 5. Write a program to count the number of upper-case alphabets present in a text file “Article.txt”. 6. Write a program that copies one file to another. Have the program read the file names from user ? 7. Write a program that appends the contents of one file to another. Have the program take the filenames from the user. 8, Write a method/function DISPLAYWORDS( ) in python to read lines from a text file STORY.1XT, and display those words, which are less than‘4 characters. [CBSE Sample Paper 2020) ° . Write a program that reads characters from the keyboard one by one, All lower case characters get stored inside the file LOWER, all upper case characters get stored inside the file UPPER and all other characters get stored inside file OTHERS. 10. Write a function in Python to count and display the number of lines starting with alphabet ‘A’ present ina text file “ LINES.TXT”. eg, the file “LINES.TXT” contains the following lines :

You might also like