Computer Science
Give the output of the following snippet:
import pickle
list1, list2 = [2, 3, 4, 5, 6, 7, 8, 9, 10], []
for i in list1:
if (i % 2 == 0 and i % 4 == 0):
list2.append(i)
f = open("bin.dat", "wb")
pickle.dump(list2, f)
f.close()
f = open("bin.dat", "rb")
data = pickle.load(f)
f.close()
for i in data:
print(i)
Python
Python Data Handling
3 Likes
Answer
4
8
Working
The code imports pickle module in Python. Initially, it creates two lists: list1 with numbers from 2 to 10 and list2 as an empty list. It then iterates through list1 and appends numbers divisible by both 2 and 4 to list2. After that, it opens a binary file named "bin.dat" in write-binary mode ("wb") and uses pickle.dump() to serialize list2 and write it to the file. The file is then closed. Later, the code opens the same file in read-binary mode ("rb") and uses pickle.load() to deserialize the data from the file into the variable data. Finally, it iterates through data and prints each element, which in this case are the numbers from list2 that satisfy the conditions (divisible by both 2 and 4).
Answered By
1 Like
Related Questions
What is the output of the following code fragment? Explain.
fout = open("output.txt", 'w') fout.write("Hello, world! \n") fout.write("How are you?") fout.close() f = open("output.txt") print(f.read())Write the output of the following code with justification if the contents of the file "ABC.txt" are:
"Welcome to Python Programming!"
f1 = open("ABC.txt", "r") size = len(f1.read()) print(size) data = f1.read(5) print(data)Anant has been asked to display all the students who have scored less than 40 for Remedial Classes. Write a user-defined function to display all those students who have scored less than 40 from the binary file "Student.dat".
Following is the structure of each record in a data file named "PRODUCT.DAT".
{"prod_code": value, "prod_desc": value, "stock": value}The values for prodcode and proddesc are strings and the value for stock is an integer.
Write a function in Python to update the file with a new value of stock. The stock and the product_code, whose stock is to be updated, are to be inputted during the execution of the function.