File Handling
File Handling
4. File Handling
Direction (Q. Nos. 1-15) Each of the question has four options out of which only one is correct.
Select the correct option as your answer.
    1. To read three characters from a file object f, we use ……… .
        (a) f.read(3)            (b) f.read()              (c) f.readline()       (d) f.readlines()
        s=myfile.read(10)
        print(s)
        s1=myfile.read(15)
        print(s1)
        myfile.close()
        (a) Education                                      (b) Education
            Hub Learning is                                    Hub
                                                               Learning is
16                                                      CBSE Sample Paper Computer Science Class XII (Term I)
       f.close( )
       (a) Delete the 3rd word from file        (b) Delete the 4th word from file
       (c) Delete the 3rd word from file at end (d) Error
                     CBSE
                     QUESTION BANK
                     Case Study Based Questions
                      1. Rohit, a student of Class 12th, is learning CSV File Module in Python. During examination, he has
                         been assigned an incomplete Python code (shown below) to create a CSV File ‘Student.csv’
                         (content shown below). Help him in completing the code which creates the desired CSV File.
                         CSV File
                         1,AKSHAY,XII,A
                         2,ABHISHEK,XII,A
                         3,ARVIND,XII,A
                         4,RAVI,XII,A
                         5,ASHISH,XII,A
                         Incomplete Code
                         import_____                            #Statement 1
                         fh = open(_____, _____, newline=‘ ’) #Statement 2
                         stuwriter = csv._____                  #Statement 3
                         data = []
                         header = [‘ROLL_NO’, ‘NAME’, ‘CLASS’, ‘SECTION’]
                         data.append(header)
                         for i in range(5):
                            roll_no = int(input(“Enter Roll Number : ”))
                            name = input(“Enter Name : ”)
                            class = input(“Class : ”)
                            section = input(“Enter Section : ”)
                            rec = [_____]                       #Statement 4
                            data.append(rec)
                         stuwriter. _____ (data)                #Statement 5
                         fh.close()
                           (i) Identify the suitable code for blank space in line marked as Statement 1.
                              (a) csv file                                      (b) CSV
CBSE QUESTION BANK
      (v) Choose the function name that should be used in the blank space of line marked as Statement 5 to
          create the desired CSV file?
         (a) dump()             (b) load()                (c) writerows()           (d) writerow()
  2. Amritya Seth is a programmer, who has recently been given a task to write a Python code to
     perform the following binary file operations with the help of two user defined
     functions/modules:
      (a) AddStudents() to create a binary file called STUDENT.DAT containing student information –
          roll number, name and marks (out of 100) of each student.
      (b) GetStudents() to display the name and percentage of those students who have a percentage
          greater than 75. In case there is no student having percentage > 75, the function displays an
          appropriate message. The function should also display the average percent.
     He has succeeded in writing partial code and has missed out certain statements, so he has left
     certain queries in comment lines. You as an expert of Python have to provide the missing
     statements and other related queries based on the following code of Amritya.
     import pickle
     def AddStudents():
        ____________ #1 statement to open the binary file to write data
        while True:
           Rno = int(input(“Rno :”))
           Name = input(“Name:”)
           Percent = float(input(“Percent :”))
           L = [Rno, Name, Percent]
           ____________ #2 statement to write the list L into the file
           Choice = input(“enter more (y/n): ”)
           if Choice in “nN”:
              break
        F.close()
     def GetStudents():
        Total=0
        Countrec=0
        Countabove75=0
        with open(“STUDENT.DAT”,“rb”) as F:
           while True:
              try:
                 ____________ #3 statement to read from the file
                 Countrec+=1
                 Total+=R[2]
                 if R[2] > 75:
                                                                                                             CBSE QUESTION BANK
                        Answer any four questions (out of five) from the below mentioned questions.
                          (i) Which of the following commands is used to open the file “STUDENT.DAT” for writing only in
                              binary format? (marked as #1 in the Python code)
                             (a) F= open(“STUDENT.DAT”,‘wb’)                        (b) F= open(“STUDENT.DAT”,‘w’)
                             (c) F= open(“STUDENT.DAT”,‘wb+’)                       (d) F= open(“STUDENT.DAT”,‘w+’)
                         (ii) Which of the following commands is used to write the list L into the binary file
                              ‘STUDENT.DAT’? (marked as #2 in the Python code)
                             (a) pickle.write(L,f)                                  (b) pickle.write(f, L)
                             (c) pickle.dump(L,F)                                   (d) f=pickle.dump(L)
                         (iii) Which of the following commands is used to read each record from the binary file
                               ‘STUDENT.DAT’? (marked as #3 in the Python code)
                             (a) R = pickle.load(F)      (b) pickle.read(r,f)       (c) r= pickle.read(f) (d) pickle.load(r,f)
                         (iv) Which of the following statement(s) are correct regarding the file access modes?
                             (a) ‘r+’ opens a file for both reading and writing. File object points to its beginning.
                             (b) ‘w+’ opens a file for both writing and reading. Adds at the end of the existing file, if it exists and
                                 creates a new one, if it does not exist.
                             (c) ‘wb’ opens a file for reading and writing in binary format. Overwrites the file, if it exists and
                                 creates a new one, if it does not exist.
                             (d) ‘a’ opens a file for appending. The file pointer is at the start of the file, if the file exists.
                         (v) Which of the following statements correctly explain the function of seek() method?
                             (a) Tells the current position within the file.
                             (b) Determines if you can move the file position or not.
                             (c) Indicates that the next read or write occurs from that position in a file.
                             (d) Moves the current file position to a given specified position
                     3. Krrishnav is looking for his dream job but has some restrictions. He loves Delhi and would take a
                        job there, if he is paid over ` 40000 a month. He hates Chennai and demands at least ` 100000 to
                        work there. In any another location, he is willing to work for ` 60000 a month. The following code
                        shows his basic strategy for evaluating a job offer.
                        pay= _________
                        location= _________
                        if location == “Mumbai”:
                            print (“I’ll take it!”)                                     #Statement 1
                        elif location == “Chennai”:
                            if pay < 100000:
                               print (“No way”)                                         #Statement 2
                            else:
                               print(“I am willing!”)                                   #Statement 3
                        elif location == “Delhi” and pay > 40000:
                            print(“I am happy to join”)                                  #Statement 4
                        elif pay > 60000:
CBSE QUESTION BANK
  4. Consider the following code and answer the questions that follow:
     Book={1:‘Thriller’, 2:‘Mystery’, 3:‘Crime’, 4:‘Children Stories’}
     Library ={‘5’:‘Madras Diaries’,‘6’:‘Malgudi Days’}
       (i) Ramesh needs to change the title in the dictionary book from ‘Crime’ to ‘Crime Thriller’. He has
           written the following command:
          Book[‘Crime’]=’Crime Thriller’
          But he is not getting the answer. Help him choose the correct command:
          (a) Book[2]=‘Crime Thriller’                             (b) Book[3]=‘Crime Thriller’
          (c) Book[2]=(‘Crime Thriller’)                           (d) Book[3] =(‘Crime Thriller’)
      (ii) The command to merge the dictionary Book with Library the command would be:
          (a) d=Book+Library                                       (b) print(Book+Library)
          (c) Book.update(Library)                                 (d) Library.update(Book)
     (iii) What will be the output of the following line of code:
          print(list(Library))
          (a) [‘5’,‘Madras Diaries’,‘6’,‘Malgudi Days’]            (b) (‘5’,’Madras Diaries’,‘6’,‘Malgudi Days’)
          (c) [‘Madras Diaries’,‘Malgudi Days’]                    (d) [‘5’,‘6’]
     (iv) In order to check whether the key 2 is present in the dictionary Book, Ramesh uses the following
          command:
          2 in Book
          He gets the answer ‘True’. Now to check whether the name ‘Madras Diaries’ exists in the
          dictionary Library, he uses the following command:
          ‘Madras Diaries’ in Library
          But he gets the answer as ‘False’. Select the correct reason for this.
          (a) We cannot use the in function with values. It can be used with keys only.
          (b) We must use the function Library.values() along with the in operator.
          (c) We can use the Library.items() function instead of the in operator.
          (d) Both (b) and (c)
      (v) With reference to the above declared dictionaries, predict the output of the following code
          fragments.
                                                                                                                   CBSE QUESTION BANK
                                      Code 1                          Code 2
                            Library=Book                  Library=Book.copy()
                            Library.pop(2)                Library.pop(2)
                            print(Library)                print(Library)
                            print(Book)                   print(Book)
                     5. Arun, during Practical Examination of Computer Science, has been assigned an incomplete
                        search() function to search in a pickled file student.dat. The file student.dat is created by his
                        teacher and the following information is known about the file.
                        l
                             File contains details of students in [roll_no,name,marks] format.
                        l
                             File contains details of 10 students (i.e. from roll_no 1 to 10) and separate list of each student is
                             written in the binary file using dump().
                               Arun has been assigned the task to complete the code and print details of roll number 1.
                        def search():
                           f = open(“student.dat”,____)                  #Statement 1
                           ____:                                         #Statement 2
                              while True:
                                 rec = pickle.____                       #Statement 3
                                 if(____):                               #Statement 4
                                    print(rec)
                           except:
                              pass
                           ____                                          #Statement 5
                            (i) In which mode, Arun should open the file in Statement 1?
                               (a) r                   (b) r+                      (c) rb                     (d) wb
                            (ii) Identify the suitable code to be used at blank space in line marked as Statement 2.
                               (a) if(rec[0]==1)       (b) for i in range(10)      (c) try                    (d) pass
                        (iii) Identify the function (with argument), to be used at blank space in line marked as Statement 3.
CBSE QUESTION BANK
                     6. Radha Shah is a programmer, who has recently been given a task to write a Python code to
                        perform the following CSV file operations with the help of two user defined functions/modules:
                            (a) CSVOpen() : to create a CSV file called BOOKS.CSV in append mode containing information of
                                books – Title, Author and Price.
                            (b) CSVRead() : to display the records from the CSV file called BOOKS.CSV where the field title
                                starts with ‘R’.
CBSE Sample Paper Computer Science Class XII (Term I)                                                           23
     She has succeeded in writing partial code and has missed out certain statements, so she has left
     certain queries in comment lines.
     import csv
     def CSVOpen():
         with open(‘books.csv’,‘______’,newline=‘ ’) as csvf: #Statement 1
            cw=______                                               #Statement 2
            ______                                                   #Statement 3
            cw.writerow([‘Rapunzel’,‘Jack’,300])
            cw.writerow([‘Barbie’,‘Doll’,900])
            cw.writerow([‘Johnny’,‘Jane’,280])
     def CSVRead():
         try:
            with open(‘books.csv’,‘r’) as csvf:
               cr=______                                            #Statement 4
               for r in cr:
                   if ______:                                       #Statement 5
                      print(r)
         except:
            print(‘File Not Found’)
     CSVOpen()
     CSVRead()
     You as an expert of Python have to provide the missing statements and other related queries
     based on the following code of Radha.
     Answer any four questions (out of five) from the below mentioned questions.
       (i) Choose the appropriate mode in which the file is to be opened in append mode (Statement 1).
          (a) w+                       (b) ab               (c) r+                             (d) a
      (ii) Which statement will be used to create a csv writer object in Statement 2?
          (a) csv.write(csvf)                               (b) csv.writer(csvf)
          (c) csvf.writer()                                 (d) cs.writer(csvf)
     (iii) Choose the correct option for Statement 3 to write the names of the column headings in the CSV
           file, BOOKS.CSV.
          (a) cw.writerow(‘Title’,‘Author’,‘Price’)         (b) cw.writerow([‘Title’,‘Author’,‘Price’])
          (c) cw.writerows(‘Title’,‘Author’,‘Price’)        (d) cw.writerows([‘Title’,‘Author’,‘Price’])
      (iv) Which statement will be used to read a csv file in Statement 4?
          (a) cs.read(csvf)                                 (b) csv.reader(csvf)
          (c) csvf.read()                                   (d) csvf.reader(cs)
      (v) Fill in the appropriate statement to check the field Title starting with ‘R’ for Statement 5 in the
          above program.
          (a) r[0][0]==‘R’           (b) r[1][0]==‘R’       (c) r[0][1]==‘R’              (d) r[1][1]==‘R’
                                                                                                                CBSE QUESTION BANK
  7. Priyank is a software developer with a reputed firm. He has been given the task to computerise
     the operations for which he is developing a form which will accept customer data as follows:
     The DATA TO BE ENTERED IS :
     Name
     Age
     Items bought (all the items that the customer bought)
     Bill amount
       (i) Choose the most appropriate data type to store the above information in the given sequence.
          (a) string, tuple, float, integer                 (b) string, integer, dictionary, float
          (c) string, integer, integer, float               (d) string, integer, list, float
24                                                                CBSE Sample Paper Computer Science Class XII (Term I)
                         (ii) Now the data of each customer needs to be organised such that the customer can be identified by
                              name followed by the age, item list and bill amount. Choose the appropriate data type that will
                              help Priyank accomplish this task.
                             (a) List                                              (b) Dictionary
                             (c) Nested Dictionary                                 (d) Tuple
                        (iii) Which of the following is the correct way of storing information of customers named ‘Paritosh’
                              and ‘Bhavesh’ with respect to the option chosen above?
                            (a) customers= {‘Paritosh’:24,[‘Printed Paper’, ‘ Penstand’], 3409, ‘Bhavesh’: 45,[‘A4 Rim’,’Printer
                                Cartridge’, ‘Pen Carton’, ‘Gift Wrap’], 8099.99 }
                            (b) customers={‘Paritosh’:[24,[‘Printed Paper’, ‘ Penstand’], 3409], ‘Bhavesh’: [45,[‘A4 Rim’,’Printer
                                Cartridge’, ‘Pen Carton’, ‘Gift Wrap’], 8099.99] }
                            (c) customers= [‘Paritosh’:24,‘Printed Paper’, ‘ Penstand’, 3409, ‘Bhavesh’: 45,‘A4 Rim’,’Printer
                                Cartridge’, ‘Pen Carton’, ‘Gift Wrap’, 8099.99 ]
                            (d) customers=(‘Paritosh’:24,[‘Printed Paper’, ‘ Penstand’], 3409, ‘Bhavesh’: 45,[‘A4 Rim’,’Printer
                                Cartridge’, ‘Pen Carton’, ‘Gift Wrap’], 8099.99 )
                        (iv) In order to calculate the total bill amount for 15 customers, Priyank
                             Statement 1 must use a variable of the type float to store the sum.
                             Statement 2 may use a loop to iterate over the values.
                             (a) Both statements are correct.
                             (b) Statement 1 is correct, but statement 2 is not.
                             (c) Both statements are incorrect.
                             (d) Statement 1 is incorrect but statement 2 is correct.
                     8. Your teacher has given you a method/function FilterWords() in Python which read lines from a
                        text file NewsLetter.TXT and display those words, which are lesser than 4 characters. Your
                        teachers intentionally kept few blanks in between the code and asked you to fill the blanks, so
                        that the code will run to find desired result. Do the needful with the following Python code.
                        def FilterWords():
                            c=0
                            file=open(‘NewsLetter.TXT’, ‘_____’) #Statement 1
                            line = file._____                           #Statement 2
                            word = _____                                #Statement 3
                            for c in word:
                                if _____:                                #Statement 4
                                   print(c)
                                   ______                               #Statement 5
                        FilterWords()
                          (i) Write mode of opening the file in Statement 1?
                             (a) a                                                 (b) ab
                             (c) w                                                 (d) r
CBSE QUESTION BANK
                         (ii) Fill in the blank in Statement 2 to read the data from the file.
                             (a) File.Read()                                       (b) file.read()
                             (c) read.lines( )                                     (d) readlines( )
                        (iii) Fill in the blank in Statement 3 to read data word by word.
                             (a) Line.Split()                                      (b) Line.split()
                             (c) line.split()                                      (d) split.word()
                        (iv) Fill in the blank in Statement 4, which display the word having lesser than 4 characters.
                             (a) len(c) ==4                                        (b) len(c)<4
                             (c) len ( )= =3                                       (d) len ( )==4
                         (v) Fill in the blank in Statement 5 to close the file.
                             (a) file.close()                                      (b) File.Close()
                             (c) Close()                                           (d) end()
CBSE Sample Paper Computer Science Class XII (Term I)                                                                                25
                                                           Answers
      1. (i) c   (ii) b (iii) c (iv) d   (v) c 2. (i) a   (ii) c (iii) a (iv) a (v) d     3. (i) b   (ii) d (iii) d (iv) c (v) d
      4. (i) b   (ii) d (iii) d (iv) b   (v) c 5. (i) c (ii) c (iii) c (iv) d     (v) c   6. (i) d   (ii) b (iii) b (iv) b   (v) a
      7. (i) d   (ii) c (iii) b (iv) a         8. (i) d   (ii) b (iii) c (iv) b   (v) a
                                                    SOLUTIONS
  1. (i) csv is the correct code to fill up the blank is                    (ii) When location = “Surat”, pay = 50000
          Statement 1, which is to be imported.                                  entered by user then statement 6 will be
     (ii) This code opens a file student.csv in write                            execute.
          mode because append() method is using.                           (iii) When location = “Any Other City”, pay =1
          So, correct missing code is                                            entered by user then statement 6 will be
          “Student.csv”, “w”                                                     execute because it does not satisfied any
    (iii) writer(fh) should be used in blank space in                            given condition.
          Statement 3. csv. writer is used to insert                       (iv) When location = “Delhi”, pay = 50000
          data to the CSV file.                                                  entered by user then statement 4 will be
    (iv) Suitable code for blank space in Statement                              execute.
          4 is roll_no, name, class, section.                               (v) When location = “Lucknow”, pay =65000
     (v) writerows() should be used in blank space                               entered by user then statement 5 will be
          in Statement 5.                                                        execute.
          writerows() function writes each sequence                     4. (i) To update the element of dictionary which
          in a list as a comma separated line of items                          is already exist, following syntax is used
          in the file.                                                                dictionary name [key] = value
  2. (i) To open the file binary, open() function is                            In question, to change the value of key 3
          used.                                                                 Ramesh have to give key instead of value.
          Correct answer is                                                     So, the correct code is
          F=open(“STUDENT.DAT”, ‘wb’), if file                                  Book [3] = ‘Crime Thriller’
          name is “STUDENT.DAT”.
                                                                           (ii) To merge two dictionaries, following
     (ii) To write the list L into file, pickle.dump                            syntax is used
          (L,F) is used. For using dump() method,
                                                                                dictionary2. update (dictionary1)
          you first have to import the pickle module.
                                                                                So, correct code to merge dictionaries
    (iii) The correct statement used in marked as #3
                                                                                Book and Library are
          is R=pickle.load(F) because load()
          method is used to load data from a binary                                       Library. update (Book)
          file.                                                           (iii) list () is used to convert the sequence types
    (iv) The correct statement regarding the file                               into lists.
          access modes is r+ opens a file for the both                    (iv) in operator considers only keys of
                                                                                dictionary. If we want to check the
                                                                                                                                     CBSE QUESTION BANK
                             correct code is csv. reader (csvf).                       4, which display the word having lesser than
                        (v) Title is the first column of CSV file, so its              4 characters.
                             index would be r [0] [0].                            (v) file.close() is used to close the file. It is
                             Condition to check the field Title starting               important to close the files as soon as you
                             with ‘R’ will be r [0] [0] = ‘R’.                         have finished your work with file.