Page 152 - PYTHON-12
P. 152

# Writing all lines in CSV file
                       Csvobj.writerows(Lines)
                       Csvfile.close()          # Closing a CSV File
                   # To read and show the content of a CSV File
                   def ShowAll():
                       # Opening CSV File for reading
                       Csvfile = open('student.csv', 'r', newline='')
                       # Reading the CSV content in object
                       Csvobj = csv.reader(Csvfile)
                       for Line in Csvobj:      # Extracting line by line content
                           print(Line)
                       Csvfile.close()          # Closing a CSV File
                   print("CSV File Handling")
                   while True:
                       Option = input("1:CreateCSV 2:CreateCSVAll 3:ShowCSV 4:Quit ")
                       if Option == "1":
                           CreateCSV1()
                       elif Option == "2":
                          CreateCSV2()
                       elif Option == "3":
                           ShowAll()
                       else:
                           break
                15.  (a)  Create a binary file “employee” that stores the records of employees and display them one by one.
                    (b)  Display the records of all those employees who are getting salaries between 25000 to 30000.

               Ans.  (a)  import pickle
                       f1 = open('emp.dat','rb')
                       e = pickle.load(f1)
                       for x in e:
                           print(x)
                       f1.close()
                    (b)  import pickle
                       f1 = open('emp.dat','rb')
                       e = pickle.load(f1)
                       for x in e:
                           if(e[x]>=25000 and e[x]<=30000):
                               print(x)
                       f1.close()
                16.  What is the output of the following code?

                       fh = open("test.txt", "r")
                       Size = len(fh.read())
                       print(fh.read(5))
               Ans.  No output.
                    Explanation. The fh.read() of line 2 will read the entire file content and place the file pointer at the end
                   of file. For the fh.read(5), it will return nothing as there are no bytes to be read from EOF. Thus print()
                   statement prints nothing.

              UNSOLVED QUESTIONS

                1.  Write appropriate statements to do the following:
                    (a)  To open a file named "RESULT.DAT" for output.                                            Python Libraries
                    (b)  To go to the end of the file at any time.

                                                                                                            4.23
   147   148   149   150   151   152   153   154   155   156   157