CBSE · 083Class XII · 2024Section E5 marks

Question 34

2 April 2024 · Computer Science (083)

(i) Differentiate between 'w' and 'a' file modes in Python.

(ii) Consider a binary file, items.dat, containing records stored in the given format:

text
{item_id: [item_name, amount]}

Write a function, Copy_new(), that copies all records whose amount is greater than 1000 from items.dat to new_items.dat.

Answer

(i) 'w' mode opens a file for writing. If the file does not exist, a new file is created. If it exists, its contents are truncated and replaced. The file pointer is positioned at the beginning.

'a' mode opens a file for appending. If the file does not exist, a new file is created. If it exists, the contents are preserved and the file pointer is placed at the end so new data is added after existing data.

(ii)

python
import pickle

def Copy_new():
    try:
        F1 = open("items.dat", "rb")
        F2 = open("new_items.dat", "wb")
        try:
            while True:
                D1 = pickle.load(F1)
                for K, V in D1.items():
                    if V[1] > 1000:
                        pickle.dump({K: V}, F2)
        except EOFError:
            pass
        F1.close()
        F2.close()
    except:
        print("File Opening Error")

Explanation

(i) 'w' truncates existing content; 'a' preserves and appends. (ii) Reads each pickled record, checks amount index [1], and writes qualifying records to the new file.