Computer Science

(i) Differentiate between r+ and w+ file modes in Python.

(ii) Consider a file, SPORT.DAT, containing records of the following structure: [SportName, TeamName, No_Players]

Write a function, copyData(), that reads contents from the file SPORT.DAT and copies the records with Sport name as “Basket Ball” to the file named BASKET.DAT. The function should return the total number of records copied to the file BASKET.DAT.

Python File Handling

5 Likes

Answer

(i)

r+ modew+ mode
Primary function is reading.Primary function is writing.
If the file does not exist, it results in an error.If the file does not exist, it creates a new file.

(ii)

def copyData():
    fobj = open("SPORT.DATA", "rb")
    fobj1 = open("BASKET.DAT", "wb")
    cnt = 0
    try:
        while True:
            data = pickle.load(fobj)
            print(data)
            if data[0] == "Basket Ball":
                pickle.dump(data, fobj1)
                cnt +=1
    except:
        fobj.close()
        fobj1.close()
    return cnt

Answered By

4 Likes


Related Questions