Test Index
File Handling in Python
© examsnet.com
Question : 26 of 37
Marks:
+1,
-0
(a) (i) What is the main purpose of
seek() and tell() method ?(ii) Consider a binary file, Cinema.dat containing information in the following structure :[Mno, Mname, Mtype]Write a function, search_copy(), that reads the content from the file Cinema.dat and copies all the details of the "Comedy" movie type to file named movie.dat.OR(b) (i) Give one difference between write() and writeline() function in text file.(ii) A Binary file, "Items.dat" has the following structure :[Icode, Description, Price]WhereIcode - Item codeDescription - Detail of itemPrice - Price of itemWrite a function
Add_data(), that takes Icode, Description and Price from the user and writes the information in the binary file "Items.dat".[CBSE 2024 Compartment]
Solution:
(a)(i)
(Python's list-writing method is
seek(offset): moves the file pointer (object) to the given byte position in the file, for example f.seek(0) takes it back to the beginning.tell(): returns the current position of the file pointer, as a number of bytes from the beginning of the file.(a)(ii)import pickledef search_copy(): f1 = open("Cinema.dat", "rb") f2 = open("movie.dat", "wb") try: while True: rec = pickle.load(f1) # [Mno, Mname, Mtype] if rec[2] == "Comedy": pickle.dump(rec, f2) except EOFError: pass f1.close() f2.close()Explanation: Cinema.dat is opened for reading in binary mode ("rb") and movie.dat for writing ("wb"). Records are read one by one with pickle.load() until EOFError marks the end of the file; every record whose Mtype is "Comedy" is written to movie.dat with pickle.dump().OR (b)(i)| write() | writelines() |
| Writes a single string to the text file. | Writes a list (sequence) of strings to the text file. |
f.write("Hello World\n") | f.writelines(["Hello\n", "World\n"]) |
writelines(); neither adds a newline by itself.)(b)(ii)import pickledef Add_data(): f = open("Items.dat", "ab") Icode = int(input("Item code: ")) Description = input("Description: ") Price = float(input("Price: ")) pickle.dump([Icode, Description, Price], f) f.close()Explanation: The file is opened in binary append mode ("ab") so earlier records are kept ("wb" also works but replaces the old contents). The three values are taken from the user and the record [Icode, Description, Price] is written with pickle.dump().© examsnet.com
Go to Question: