0% found this document useful (0 votes)
41 views72 pages

Conlib Filehandlingtest1answerkey 20250305094905-1

The document contains a test answer key for file handling in Python, covering various topics such as file modes, reading and writing files, and methods like tell() and seek(). Each question is followed by the correct answer, with explanations for certain concepts. The test assesses knowledge on file operations, including syntax and functionality related to file handling in Python.

Uploaded by

bridjet selvaraj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views72 pages

Conlib Filehandlingtest1answerkey 20250305094905-1

The document contains a test answer key for file handling in Python, covering various topics such as file modes, reading and writing files, and methods like tell() and seek(). Each question is followed by the correct answer, with explanations for certain concepts. The test assesses knowledge on file operations, including syntax and functionality related to file handling in Python.

Uploaded by

bridjet selvaraj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

File handling Test1 answer key

MM :295

1 The modes of file in python are (a) r (b) r+(c) w (d) All of the these 1

ANS: (d)

2 To open a file "c:marks.txt" for reading, we use


(a) file_read = open("c:marks.txt", "r")
(b) file_read = open("c:marks.txt", "r") 1
(c) file_read = open(file = "c:marks.txt", "r")
(d) file_read = open(file = "c:marks.txt", "r")

ANS: (b)

3 To read two characters from a file object "file_read"


(a) file_read.read(2)
(b) file_read(2) 1
(c) file_read(read,2)
(d) file_read.readlines(2)

ANS: (a)

4 To read the content of the file as a string via a file object "f" (a) f.read(2) (b) f.read()(c) f=file.readline() (d)
1
f.readlines()
ANS: (b)

5 The readlines() returns


(a) only first line from the file
(b) only last line from the file 1
(c) all lines from the file
(d) none of the above

ANS: (c)

6 What is the use of tell() method in Python?


(a) returns the current position of record pointer within the file
(b) returns the end position of record pointer within the file 1
(c) returns the current position of record pointer within the line
(d) none of the above

ANS: (a)

7 What is the syntax of rename() a file?


(a) rename(current_file_name, new_file_name)
(b) rename(new_file_name, current_file_name,) 1
(c) rename(()(current_file_name, new_file_name))
(d) none of these

ANS: (a)

8 seek() method in files used for


(a) sets the file's current position at the offset 1
(b) sets the file's previous position at the offset
(c) sets the file's current position within the file
(d) none of these

ANS: (a)

9 What is the use of tell() method in python?


(a) tells you the current position within the file
(b) tells you the end position within the file 1
(c) tells you the file is opened or not
(d) none of these

ANS: (a)

10 What is the syntax of remove() a file in python?


(a) remove(file_name)
(b) remove(new_file_name, current_file_name,) 1
(c) remove(() , file_name))
(d) none of these

ANS: (a)

11 What is the pickling?


(a) It is used for object serialization
(b) It is used for object deserialization 1
(c) None of the mentioned
(d) All of the mentioned

ANS: (a)
12 Which of the following statement is not true regarding the opening modes of a file?
(a) When you open a file for reading, if the file does not exist, an error occurs.
(b) When you open a file for writing, if the file does not exist, an error occurs.
1
(c) When you open a file for reading, if the file does not exist, the program will open an empty file.
(d) When you open a file for writing, if the file does not exist, a new file is created.
(e) When you open a file for writing, if the file exists, the existing file is overwritten with the new file.

ANS: (c)

13 Which of the following commands can be used to read "n" number of characters from a file using the file object
1
<file>? (a) File.read(n) (b) N = file.read()(c) File.readline(n) (d) File.readlines()

ANS: (a)

14 Which of the following commands can be used to read the entire contents of a file as a string using the file object
1
<File>? (a) File.read(n) (b) File.read()(c) File.readline() (d) File.readlines()

ANS: (b)

15 Which of the following commands can be used to read the next line in a file using the file object <File>? (a)
1
File.read(n) (b) File.read()(c) File.readline() (d) File.readlines()

ANS: (c)

16 What does the <readlines()> method returns? (a) Str(b) A list of lines(c) List of single characters(d) List of integers 1

ANS: (b)

17 Which of the following command is used to open a file "d:temp.txt" for writing in binary format only? (a) fout = 1
open("d:story.txt", "wb") (b) fout = open("d:temp.txt", "wb") (c) fout = open(file = "d:temp.txt", "wb+") (d) fout =
open(file = "d:temp.txt", "wb+")

ANS: (b)

18 Which of the following functions do you use to write data in the binary format? (a) Write (b) Output(c) Dump (d)
1
Send

ANS: (c)

19 Which of the following are the attributes related to a file object? (a) Closed (b) Mode (c) Filename (d) Rename 1

ANS: (a) and (b)

20 What will be the output of the following code snippet? If we assume that file contains the given text:

Str="CBSE Class XII Python Examination 2020"

ANS: Name of the file: myfile.txt

21 What is the correct syntax of open() function?


(a) File = open(file_name[, access_mode][, buffering]) 1
(b) File object = open(file_name [, access_mode][,buffering])
(c) File object = open(file_name)
(d) None of the above

ANS: (b)

22 Write a statement in Python to open a text file STORY.TXT, so that the new contents can be added at the end of it. 1

ANS: File = open("STORY.TXT","w")

23 Write the difference between the following.


(a) f = open('diary.txt', 'a') 1
(b) f = open('diary.txt', 'w')

ANS: (a) It will open the file in append mode and data will be added at the end of the file only.
(b) It will open the file in write mode if file already exists then previous data will be erased.

24 Differentiate the following:


(a) f = open('diary.txt', 'r') 1
(b) f = open('diary.txt', 'w')

ANS: (a) It opens the file in reading mode only in text format.
(b) It opens the file in writing mode only in text format. If the file exists, then it erases the previous data.

25 Difference between tell() and seek(). 1

ANS: Tell(). It returns the current position of the file object (Integer value).
Seek(). It position the file object at the specified location.

26 Write the syntax to open a file "para.txt" in read mode. 1


ANS:

27 Write the codings to display the content of file "welcome.txt". 1

ANS:

28

Write the output of the given program:

ANS: Location of the cursor is : 36

29 A text file “Quotes.Txt” has the following data written in it:


"Living a life you can be proud of Doing your best
Spending your time with people and activities that are important to you
2
Standing up for things that are right even when it’s hard
Becoming the best version of you."
Write a user defined function to display the total number of words present in the file.
ANS:

30 What is .csv file? 1

ANS: Comma Separated Values. It is a simple file format which store into the tabular format. This format file can
be open in notepad or spreadsheet. It works better as its takes less memory space and faster in data manipulation.

31 Write the difference between “r” and “rb” mode. 1

ANS:

r It opens the file in reading mode only in text format.

rb It opens the file reading only in binary format.

32 How relative path is different from absolute path. 1

ANS: The absolute path is the full path from we want to open/create the file.
The relative path is the path to some file with respect to your current working directory.
33 Nancy intends to position the file pointer to the beginning of a text file. Write Python statement for the same
1
assuming F is the Fileobject.

ANS: F.seek(0)

34 Write a statement in Python to open a text file STORY.TXT so that new contents can be added at the end of it. 1

ANS:

35 Write a statement in python to perform the following operations:


• To open a text file “MYPET.TXT” in write mode. 1
• To open a text file “MYPET.TXT” in read mode.

ANS:

36 Differentiate between file modes r+ and rb+ with respect to Python. 1

ANS: Difference

r It opens the file in reading and writing.

It opens the file in reading and writing for binary


rb+
format.

37
1
Observe the following code and answer the questions that follow: (i) What type
(Text/Binary) of file is Mydata?
(ii) Fill the Blank 1 with statement to write “ABC” in the file “Mydata”.

ANS: (i) Text File (default mode)


(ii) File.write(“ABC”)

38

Write the output of the given program:

ANS: 22

39 Assume that file “tear.txt”, already contain “I love my India” in the file. What will be the output of the given program:

ANS: 28

40 Assume that file “tear.txt”, already contain “I love my India” in the file. What will be the output of the given program: 1
ANS: 13

41 A text file “Quotes.Txt” has the following data written in it:


Living a life you can be proud of
Doing your best
Spending your time with people and activities that are important to you
Standing up for things that are right even when it’s hard
1
Becoming the best version of you.

Write the output of the given program.

ANS: ife y

42 The syntax of seek() is: [CBSE 2023]

file_object.seek(offset[,reference_point]) 1

What is the default value of reference_point? (a) 0 (b) 1 (c) 2 (d) 3

ANS: (a)

43 Which of the following statement is not correct? [CBSE 2021] (a) We can write 1
content into a text file opened using 'w' mode (b) We can write content into a text file opened using 'w+' mode
(c) We can write content into a text file opened using 'r' mode (d) We can write content into a text file
opened using 'r+' mode

ANS: (c)

44 Which of the following option is the correct Python statement to real and display the first 10 characters of a text file
"Notes.txt"?[CBSE 2021]

(a) F=open('Notes.txt'); print(F.load(10)) 1

(b) F=open('Notes.txt'); print(F.dump(10)) (c) F=open('Notes.txt'); print(F.read(10)) (d)


F=open('Notes.txt'); print(F.write(10))

ANS: (c)

45 Which of the following is not a correct Python statement to open a text file "Notes.text" to write content into
it?[CBSE 2021]
1
(a) F=open('Notes.txt','w')
(b) F=open('Notes.txt','a') (c) F=open('Notes.txt','A') (d) F=open('Notes.txt','w+')

ANS: (c)

46 A text file opened using the following statement:

MyFile=open('Notes.txt')
1
Which of the following is the correct Python statement to close it?[CBSE 2021] (a)
MyFile=close('Notes.txt') (b) MyFile.close('Notes.txt') (c)cose.MyFile() (d) MyFile.close()
ANS: (d)

47 Which of the following option is the correct usage for the tell() of a file object?[CBSE 2021]

(a) It places the file pointer at a desired offset in a file.


1
(b) It returns the entire content of a file. (c) It returns the byte position of the file pointer as an integer. (d)
It tells the details about the file.

ANS: (b)

48 Which of the following statement is icorrect in the context of picked binary files?

(a) csv module is used for reading and writing objects in binary files.
1
(b) pickle module is used for reading and writing objects in binary files. (c) load() of the pickle module is used
to read objects. (d) dump() of the pickle module is used to read objects.

ANS: (a)

49 What is the significance of the seek() method? [CBSE 2021] (a) It seeks the absolute path of the file.
(b) It tells the current byte position of the file pointer within the file. (c) It places the file pointer at a desired 1
offset within the file. (d) It seeks the entire content of the file.

ANS: (c)

50 If the following statement is used to read the contents of a textfile object F:[CBSE 2021]

x=F.readlines() 1

Which of the following is the correct data type of x? (a) string (b) list (c) tuple (d) dictionary
ANS: (b)

51 Suppose the content of a text file Notes.txt is:

"The.way to get started is to quit talking and begin doing"

What will be the output of the following Python code? [CBSE 2021] F=open (Notes.txt") 1
F.seek(29) S=F.read() print(S) (a) The way to get started is to (b) quit talking and
begin doing (c) The way to get started is to quit talking and begin doing (d) gniod nigeb dna gniklat tiuq ot si
detrats teg ot yaw eht

ANS: (b)

52 Which of the following Python modules is imported to store and retrieve objects using the process of serialization
and deserializaton?[CBSE 2021]
1
(a) csv

(b) binary (c) math (d) pickle

ANS: (a)

53 Which of the following function is used with the csv module in Python to read the contents of a csv file into an
object?
1
(a) readrow()

(b) readrows() (c) reader() (d) load()

ANS: (c)

54 Suppose the content of a text file "Rhymes.txt" is as follows:[CBSE 2021] 1


Jack & Jill
went up the hill What will be the output of the following Python code? F = open ("Rhymes.txt") L =
F.readlines () for i in L: S=i, split () print(len(S), end="#") (a) 2#4# (b)
3#4# (c) 2# (d) 7#

ANS: (d)

55 Suppose the content of "Thymes.txt" is

Good Morning Madam


1
What will be the output of the following Python code? [CBSE 2021] F=
open("Rhymes.txt") L = F.read().split () for W in L: if W.lower()== W[::–1].lower():
print (W) (a) Good (b) Morning (c) Madam (d) Error

ANS: (c)

56 Suppose the content of "Thymes.txt" is

Hickory Dickory Dock


1
The mouse went up the clock What will be the output of the following Python code? F =
open("Rhymes.txt") L = F.readlines() X = ["the", "ock"] for i in L: for W in i.split(): if W in X:
print (W, end = "*"] (a) the* (b) Dock*The*the*clock* (c) Dock*the*clock* (d) Error

ANS: (d)

57 What is a CSV file? (a) A file that contains human-readable text (b) A file that contains binary data (c) A file
1
that contains comma-separated values (d) None of the above
ANS: (c)

58 What is a relative path?

(a) A path that specifies the location of a file relative to the root directory
1
(b) A path that specifies the location of a file relative to the current directory (c) A path that specifies the
location of a file using the full file path (d) None of the above

ANS: (b)

59 What is an absolute path?

(a) A path that specifies the location of a file relative to the root directory
1
(b) A path that specifies the location of a file relative to the current directory (c) A path that specifies the
location of a file using the full file path (d) None of the above

ANS: (c)

60 What is the file mode 'r' in Python?

(a) Read mode (b) Write mode 1


(c) Append mode (d) None of the above

ANS: (a)

61 What is the file mode 'w' in Python?

(a) Read mode 1


(b) Write mode (c) Append mode (d) None of the above
ANS: (b)

62 What is the file mode 'a' in Python? (a) Read mode (b) Write mode (c) Append mode (d) None of the
1
above

ANS: (c)

63 What is the output of the following code?

with open("example.txt", "w") as f:


1
f.write("Hello, World!") with open("example.txt", "r") as f: print(f.read()) (a) Hello, World!
(b) example.txt (c) None of the above (d) An error will occur

ANS: (a)

64 Which of the following is NOT a type of file in Python? (a) Text file (b) Binary file (c) CSV file (d) JSON file 1

ANS: (d)

65 What is a text file? (a) A file that contains human-readable text (b) A file that contains binary data (c)
1
A file that contains comma-separated values (d) None of the above

ANS: (a)

66 What is a binary file?


(a) A file that contains human-readable text 1

(b) A file that contains binary data (c) A file that contains comma-separated values (d) None of the above
ANS: (b)

67 Which of the following modes is used to open a text file for reading?

(a) 'r' 1

(b) 'w' (c) 'a' (d) 'x'

ANS: (a)

68 Which of the following modes is used to open a text file for both reading and writing?

(a) 'r' 1
(b) 'w' (c) 'a' (d) 'r+'

ANS: (a)

69 What is the purpose of the with statement when working with files?
(a) To open the file in read mode
1
(b) To open the file in write mode (c) To ensure that the file is closed properly after use (d) To manipulate the
data in the file

ANS: (c)

70 Which method is used to write a single line of text to a file?


1
(a) write()
(b) writelines() (c) read() (d) readline()

ANS: (a)

71 Suppose the content of "Rhymes.txt" is:

Baa baa black sheep,


1
have you any wool? What will be the output of the following Python code? F = open("Thymes.txt")
S = F.read() L=S.split () for i in L: if len(i) %3 1 = 0: print(i, end= " ") (a)
Baa baa you any (b) black have wool? (c) black sheep, have wool? (d) Error

ANS: (b)

72 Suppose the content of "Rhymes.txt" is:

One, two, three, four, five


1
Once I caught a fish alive. What will be the output of the following Python code? F = open("Thymes.txt")
S = F.read() L=S.split () print (S.count('e',20)) (a) 20 (b) 1 (c) 3 (d) 6

ANS: (c)

73 Which of the following is a function/method of the pickle module?[CBSE 2021]

(a) reader() 1
(b) writer() (c) load() (d) read()

ANS: (c)

74 Which of the following statement is icorrect in the context of picked binary files?[CBSE 2021] 1
(a) csv module is used for reading and writing objects in binary files.
(b) pickle module is used for reading and writing objects in binary files. (c) load() of the pickle module is used
to read objects. (d) dump() of the pickle module is used to read objects.

ANS: (a)

75 In the following questions, a statement of assertion (A) is followed by a statement of reason (R). Choose the correct
answer out of the following choices.

Assertion (A): In Python, a text file can only be opened in read mode or write mode, but not both at the same time.

Reason (R): (a) The read mode allows the user to read the content of the file. (b) The write mode 1
allows the user to modify or overwrite the content of the file. (a) Both Assertion (A) and Reason (R) are true and
Reason (R) is the correct explanation of Assertion (A) (b) Both Assertion (A) and Reason (R) are true and Reason
(R) is not the correct explanation of Assertion (A) (c) Assertion (A) is true but Reason (R) is false (d) Assertion
(A) is false but Reason (R) is true

ANS: (a)

76 In the following questions, a statement of assertion (A) is followed by a statement of reason (R). Choose the correct
answer out of the following choices.

Assertion (A): In Python, a text file can only be opened in read mode or write mode, but not both at the same time.

Reason (R): (a) This is a recommended practice to ensure that the file is closed even if an exception occurs. 1
(b) The with clause can also reduce the amount of boilerplate code needed to open and close the file..
(a) Both Assertion (A) and Reason (R) are true and Reason (R) is the correct explanation of Assertion (A)
(b) Both Assertion (A) and Reason (R) are true and Reason (R) is not the correct explanation of Assertion (A)
(c) Assertion (A) is true but Reason (R) is false (d) Assertion (A) is false but Reason (R) is true
ANS: (a)

77 In the following questions, a statement of assertion (A) is followed by a statement of reason (R). Choose the
correct answer out of the following choices. Assertion (A): In Python, a text file can only be opened in read mode or
write mode, but not both at the same time. Reason (R): (a) The write() method appends the string to the end of the
file. (b) The write() method returns the number of characters written to the file. (a) Both Assertion (A) 1
and Reason (R) are true and Reason (R) is the correct explanation of Assertion (A) (b) Both Assertion (A) and
Reason (R) are true and Reason (R) is not the correct explanation of Assertion (A) (c) Assertion (A) is true but
Reason (R) is false (d) Assertion (A) is false but Reason (R) is true

ANS: (a)

78 In the following questions, a statement of assertion (A) is followed by a statement of reason (R). Choose the correct
answer out of the following choices. Assertion (A): In Python, the read() method can be used to read the entire
content of a text file as a single string. Reason (R): (a) The read() method reads the file from the current position of
the file pointer. (b) The read() method raises an IOError exception if the file is not readable. 1
(a) Both Assertion (A) and Reason (R) are true and Reason (R) is the correct explanation of Assertion (A)
(b) Both Assertion (A) and Reason (R) are true and Reason (R) is not the correct explanation of Assertion (A)
(c) Assertion (A) is true but Reason (R) is false (d) Assertion (A) is false but Reason (R) is true

ANS: (a)

79 In the following questions, a statement of assertion (A) is followed by a statement of reason (R). Choose the correct
answer out of the following choices. Assertion (A): Opening a text file using 'w' mode deletes the existing content of
the file. Reason (R): 'w' mode opens the file for writing and truncates the file to zero length, which means all the
existing content of the file will be deleted. (a) Both Assertion (A) and Reason (R) are true and Reason (R) is the 1
correct explanation of Assertion (A) (b) Both Assertion (A) and Reason (R) are true and Reason (R) is not the
correct explanation of Assertion (A) (c) Assertion (A) is true but Reason (R) is false (d) Assertion (A) is false but
Reason (R) is true
ANS: (a)

80 Which method is used to write multiple lines of text to a file? (a) write() (b) writelines() (c) read() (d)
1
readline()

ANS: (b)

81 Which method is used to read the entire contents of a file as a string?

(a) write() 1

(b) writelines() (c) read() (d) readline()

ANS: (c)

82 Which method is used to read a single line of text from a file?

(a) write() 1
(b) writelines() (c) read() (d) readline()

ANS: (d)

83 Which method is used to read all the lines of text from a file into a list?

(a) write() (b) writelines() 1

(c) read() (d) readlines()

ANS: (d)

84 Which method is used to move the file pointer to a specific position in the file? 1
(a) seek()
(b) tell() (c) read() (d) readline()

ANS: (a)

85 Which mode is used to open a binary file for reading?

(a) 'r' 1

(b) 'rb' (c) 'rb+' (d) 'w'

ANS: (b)

86 Which mode is used to open a binary file for writing?


(a) 'r' 1

(b) 'rb' (c) 'wb' (d) 'w+'

ANS: (c)

87 Which method is used to write data to a binary file?

(a) write() 1

(b) dump() (c) writelines() (d) None of the above

ANS: (b)

88 Which method is used to read data from a binary file?


1
(a) read()
(b) load() (c) readline() (d) None of the above

ANS: (b)

89 Which of the following is used to import the pickle module?

(a) import binary 1

(b) import pickle (c) import csv (d) import file

ANS: (b)

90 What is the output of the following code?

import pickle
1
data = [1, 2, 3, 4, 5] with open("example.pkl", "wb") as f: pickle.dump(data, f) with
open("example.pkl", "rb") as f: loaded_data = pickle.load(f) print(loaded_data) (a) [1, 2, 3, 4, 5] (b)
example.pkl (c) None of the above (d) An error will occur

ANS: (a)

91 Which method is used to append data to a binary file?


(a) append() 1

(b) write() (c) dump() (d) None of the above

ANS: (d)

92 In the following questions, a statement of assertion (A) is followed by a statement of reason (R). Choose the correct
1
answer out of the following choices.
Assertion (A): The 'readline()' method reads a single line of text from a file.
Reason (R): The 'readline()' method reads the specified number of characters from the current position in the file, or
if no size is specified, it reads a single line of text from the file and returns it as a string. (a) Both Assertion (A) and
Reason (R) are true and Reason (R) is the correct explanation of Assertion (A) (b) Both Assertion (A) and Reason
(R) are true and Reason (R) is not the correct explanation of Assertion (A) (c) Assertion (A) is true but Reason (R)
is false (d) Assertion (A) is false but Reason (R) is true

ANS: (c)

93 In the following questions, a statement of assertion (A) is followed by a statement of reason (R). Choose the correct
answer out of the following choices.

Assertion (A): The 'readlines()' method reads all the lines of text from a file and returns them as a list of strings.

Reason (R): The 'readlines()' method reads the specified number of lines from the file, or if no size is specified, it 1
reads all the lines of text from the file and returns them as a list of strings. (a) Both Assertion (A) and Reason (R)
are true and Reason (R) is the correct explanation of Assertion (A) (b) Both Assertion (A) and Reason (R) are true
and Reason (R) is not the correct explanation of Assertion (A) (c) Assertion (A) is true but Reason (R) is false
(d) Assertion (A) is false but Reason (R) is true

ANS: (b) Both A and R are true and R is not the correct explanation for A

94 In the following questions, a statement of assertion (A) is followed by a statement of reason (R). Choose the correct
answer out of the following choices.
Assertion (A): The 'seek()' method is used to move the file pointer to a specified position in the file.
1
Reason (R): The 'seek()' method is used to move the file pointer to the end of the file, which is useful for appending
data to the end of the file. (a) Both Assertion (A) and Reason (R) are true and Reason (R) is the correct
explanation of Assertion (A) (b) Both Assertion (A) and Reason (R) are true and Reason (R) is not the correct
explanation of Assertion (A) (c) Assertion (A) is true but Reason (R) is false (d) Assertion (A) is false but Reason
(R) is true

ANS: (c) A is True but R is False

95 In the following questions, a statement of assertion (A) is followed by a statement of reason (R). Choose the correct
answer out of the following choices.

Assertion (A): The 'tell()' method returns the current position of the file pointer in the file.
1
Reason (R): The 'tell()' method returns the size of the file in bytes. (a) Both Assertion (A) and Reason (R) are true
and Reason (R) is the correct explanation of Assertion (A) (b) Both Assertion (A) and Reason (R) are true and
Reason (R) is not the correct explanation of Assertion (A) (c) Assertion (A) is true but Reason (R) is false
(d) Assertion (A) is false but Reason (R) is true

ANS: (d) A is false but R is True

96 In the following questions, a statement of assertion (A) is followed by a statement of reason (R). Choose the correct
answer out of the following choices.

Assertion (A): The 'writelines()' method writes a list of strings to a file, with each string representing a line of text.
1
Reason (R): The 'writelines()' method writes a single string to a file, with each newline character ('n') representing a
new line of text. (a) Both Assertion (A) and Reason (R) are true and Reason (R) is the correct explanation of
Assertion (A) (b) Both Assertion (A) and Reason (R) are true and Reason (R) is not the correct explanation of
Assertion (A) (c) Assertion (A) is true but Reason (R) is false (d) Assertion (A) is false but Reason (R) is true

ANS: (c) A is True but R is False

97 In the following questions, a statement of assertion (A) is followed by a statement of reason (R). Choose the correct
1
answer out of the following choices.
Assertion (A): Binary files can only be opened in read mode.
Reason (R): Binary files are not writable, and can only be read from. (a) Both Assertion (A) and Reason (R) are
true and Reason (R) is the correct explanation of Assertion (A) (b) Both Assertion (A) and Reason (R) are true
and Reason (R) is not the correct explanation of Assertion (A) (c) Assertion (A) is true but Reason (R) is false
(d) Assertion (A) is false but Reason (R) is true

ANS: (d) A is false but R is True.

98 In the following questions, a statement of assertion (A) is followed by a statement of reason (R). Choose the correct
answer out of the following choices. Assertion (A): The dump() method in the pickle module is used to write data to
a binary file. Reason (R): The dump() method serializes Python objects into a binary format that can be written to a
1
file. (a) Both Assertion (A) and Reason (R) are true and Reason (R) is the correct explanation of Assertion (A)
(b) Both Assertion (A) and Reason (R) are true and Reason (R) is not the correct explanation of Assertion (A)
(c) Assertion (A) is true but Reason (R) is false (d) Assertion (A) is false but Reason (R) is true

ANS: (a) Both A and R are true and R is the correct explanation for A.

99 Mr. Iqbal is a programmer, who has recently joined the company and given a task to write a python code to perform
the following binary file operations with the help of two user defined functions/modules:
(a) Add() to create a binary file called school.dat containing student information – roll number, name,age
and marks of English, Maths and Science(out of 100) of each student.

(b) Display() to display the information of all students. He has succeeded in writing partial code 5
and has missed out certain statements, so he has left certain queries in comment lines. You as an expert of Python
have to provide the missing statements. import ____________ # statement 1 to
import module/package def add(): st={} file =open('school.dat','____')
# Statement 2 to append the record in binary file. ch='Y' while ch=='Y' or ch=='y':
admno=int(input("enter the admission number:")) name=input("enter
the name: ") age=int(input("enter the age: ")) engmarks=int(input("enter
english marks: ")) scienmarks=int(input("enter science marks: "))
mathmarks=int(input("enter maths marks: ")) st['admno']=admno
st['name']=name st['age']=age st['english']=engmarks
st['maths']=mathmarks st['science']=scienmarks
pickle.dump(st,________) # statement 3 to specify object
ch=input("do you wish to continue: ") file.close() def display(): st={}
file=open('school.dat','rb') try: while True: st=pickle._________(file)
# statement 4 to store data in st. print(st) except EOFError: print("error")
file._______ # statement 5 to close file object. (a) Write the statement to import module.
(b) Write the statement to append the record in binary. (c) Write the statement to specify object.
(d) Write the statement to store data in st. (e) Statement to close the five object.

ANS: (a) import (b) ab (c) file (d) load

(e) close()

100 Nisha, an intern in ABC Pvt. Ltd., is developing a project using the csv module in Python. She has partially
developed the code as follows leaving out statements about which she is not very confident. The code also contains
errors in certain statements. Help her in completing the code to read the desired CSV File named "Employee.csv"

#csv File Content

ENO,NAME,DEPARTMENT 012 E1,ROSHAN SHARMA, ACCOUNTS 1


E2,AASMA KHALID, PRODUCTION E3,AMRIK GILL, MARKETING E4,SARAH
WILLIAMS,HUMAN PERSOURCE #incomplete Code with Errors import CSV#Statement-1
with open (____, ____' newline='')as File:#Statement-2 ER = csv:____
#Statement-3 for.R in range(ER) : #Statement-4
if____=="Accounts" : #Statement-5
print(__, __) #Statement-6 (a) Nisha gets an Error for the module name used
in Statement-1. What should she write in place of CSV to import the correct module? (b) Identify the missing
code for blank spaces in the line marked as Statement-2 to open the mentioned file. (c) Name the function
name (with parameter) that should be used in the line marked as Statement-3. (d) Nisha gets an Error in
Statement-4. What should she write to correct the statement? (e) Write the suitable code for blank space
in Statement-5 to match every row's 3rd property with "ACCOUNTS".

ANS: (a) Csv (b) "Employes.csv","x" (c) reader(File) (d) for R is ER:

(e) R[2]

101 Mr. Mathew is a programmer, who has recently joined the company and given a task to write a python code to
perform update operation in binary file (stud.dat) which contain admno (Admission No) and fee(Fee paid by
student).

He has succeeded in writing partial code and has missed out certain statements, You as an expert of
Python have to provide the missing statements.

# Update a record. import ___________ st={} flag=0


file=open("__________","rb+") search=int(input("Enter Admission Number whose fee is to be
updated : ")) amt=int(input("How much to be increased : ")) try: while True: 1
Try: pos=file.___________ st=pickle.load(file)
if st['admno'] == search: st['fee']+=amt
file._______(pos) pickle._______(st,file)
print("Record Updated") flag=1 except EOFError:
if flag==0: print("Record Not Found")
file.close() (a) # statement 1 to import module/package (b) # statement 2 to open
binary file. (c) # statement 3 to store file pointer position (d) # statement 4 to place the file pointer at
specified position (e) # statement 5 to store the data. (f) Which of the following commands is used to
write the list LST into the binary file (FILE is file object)? (i) pickle.write(LST,FILE) (ii)
pickle.write(FILE, LST) (iii) pickle.dump(LST,FILE) (iv) FILE=pickle.dump(LIST)

ANS: (a) import pickle (b) stud.dat

(c) file.tell()

(d) file.seek(pos) (e) pickle.dump(st,file) (f) (iii) pickle.dump(LST,FILE)

102 Write a python program to accept a line from the user and store that in a file “story.txt”. 2

ANS:

103 Write a python program to accept the multiple lines from the user and store is into the file. 2

ANS:
104 Write the python program using writelines() function to store the following data:
2
[Filename: ch4/ch-4_Q10]

ANS:

105 Write a program to read and display the content of the "multiline.txt". [Filename: ch4/ch-4_Q11] 2

ANS:

106 Write a program to read the content of the file line by line and display. Assuming that file name is “multiline.txt”. 2

ANS:

107 Write a program to Read the content of the file line by line and print without ‘n’. Assuming that file name is
2
“multiline.txt”.
ANS:

108 Write a function countmy( )in Python to read the text file "DATA.TXT" and count the number of times "my" occurs in
the file.
For example if the file "DATA.TXT" contains:
2
"This is my website. I have displayed my preferences in the CHOICE section."
The countmy( ) function should display the output as:
"my occurs 2 times".

ANS:
109 Write a method in Python to read lines from a text file INDIA.TXT, to find and display the occurrence of the word

"India".

ANS:

110 Write a function to count the “me” and “my” in a file “India.txt”. 2
ANS:

111 Write a function to count the Upper case vowel in file “All.txt”. 2

ANS:

112 Write a function to copy all the upper case words to another file. 2
ANS:

113 Write a function to display the alternate lines from the file. 2

ANS:

114 Write a function to read the content from the file and display each word in reverse order. 2
ANS:

115 Write a function to read the content from the file and print all the upper case word. 2

ANS:

116 Write a function to read the content from the file “Story.txt”. The function will take a string as parameter
2
and search the string into the file.
ANS:

117 Write the program to count the number of characters in the file “India.txt”. 3

ANS:
118 Write the program using function to count the lower case vowel in the file “India.txt”. 3

ANS:

119 Write a program to create a duplicate copy of the file. 3

ANS:

120 Write a function to read the content from the "quotes.txt" and transfer the content to the file "Duplicate.txt" but while
transfer all the upper case character to lower case character, lower case character to uppercase character and rest 3
of the character as it is.
ANS:

121 Write a program to save the following records in laps1.csv.


ADMNO NAME AGE
3
1151, Ajay, 12
1152, Chandrika, 14
ANS:

122 Write a program to read the records from laps.csv. 3

ANS:

123 Write a program to save the dictionary records to teacher.csv file.


sno,teacher,subject 3
1,Shilpa,english
2,Swati,computer
3,Farhat,chemistry

ANS:

124 Write a program to read the content of teacher.csv file in dictionary.


teacher.csv
sno,teacher,subject
3
1,Shilpa,english
2,Swati,computer
3,Farhat,chemistry

ANS:

125 Define a function remove_newline() which will remove new line from sample.txt 3
ANS:

126 Write a function read the content and transfer all the word which start with lower case letter to another file. 3

ANS:

127 Write a method in Python to read lines from a text file MYNOTES.TXT, and display those lines, which are
3
starting with the alphabet ―K.
ANS:

128 Write the function to read the content from the file display the word which are having the length of exactly 4
3
characters.

ANS:

129 Write a function addrecord() a add new record to the binary file “employee” using list. The list should consist
3
of employee number, employee name and salary.
ANS:

130 Write a function readall() the record from the binary file “employee” and display all the records. 3

ANS:

131 Write a function search () to search a record in a binary file according to the employee number entered by the
3
user. Also display the message “Record not found” in case record not found in the file.
ANS:

132 Write a function update () to update the record in the binary file “employee”, which consist of employee number,
3
employee name and salary. The updation should be done on the basis of employee number entered by the user.
ANS:

133 Write a function delrecord() to delete the record form the binary file “employee”. The record should be delete
3
on the basis of employee number.
ANS:

134 Write a function to read the content from the file “India.txt”, and store the frequency of each word in dictionary and
display the dictionary in the screen. 4
Content of the file is:
‘‘India is the fastest growing economy.
India is looking for more investments around the globe.
The whole world is looking at India as a great market.
Most of the Indians can foresee the heights that India is capable of reaching.’’
Output of the file:
{‘India’: 4, ‘is’: 4, ‘the’: 4, ‘fastest’: 1, ‘growing’: 1, ‘economy.’: 1, ‘looking’: 2, ‘for’: 1, ‘more’: 1, ‘investments’: 1,
‘around’: 1, ‘globe.’: 1, ‘The’: 1, ‘whole’: 1, ‘world’: 1, ‘at’: 1, ‘as’: 1, ‘a’: 1, ‘great’: 1, ‘market.’: 1, ‘Most’: 1, ‘of’: 2,
‘Indians’: 1, ‘can’: 1, ‘foresee’: 1, ‘heights’: 1, ‘that’: 1, ‘capable’: 1, ‘reaching.’: 1}

ANS:

135 Write a function to read the content from the file “India.txt”, and store the frequency of each character in dictionary
and display the dictionary in the screen.
Content of the file is:
‘‘India is the fastest growing economy. 4
India is looking for more investments around the globe.
The whole world is looking at India as a great market.
Most of the Indians can foresee the heights that India is capable of reaching.’’
Output is:
{'I': 5, 'n': 15, 'd': 7, 'i': 15, 'a': 17, ' ': 39, 's': 13, 't': 15, 'h': 10, 'e': 20, 'f': 5, 'g': 8, 'r': 9, 'o': 17, 'w': 3, 'c': 4, 'm': 4, 'y': 1,
'.': 4, 'n': 4, 'l': 6, 'k': 3, 'v': 1, 'u': 1, 'b': 2, 'T': 1, 'M': 1, 'p': 1}

ANS:

136 Write a function addrecord() a add new record to the binary file “student” using list. The list should consist of student
4
number, student name and marks of the student.
ANS:

137 Write a function readall() the record from the binary file “student” and display all the records. 4

ANS:

138 Write a function search () to search a record in a binary file according to the student number entered by the user.
4
Also display the message “Record not found” in case record not found in the file.
ANS:

139 Write a function update () to update the record in the binary file “student”, which consist of student number, student
4
name and marks. The updation should be done on the basis of student number entered by the user.
ANS:

140 Write a function delrecord() to delete the record form the binary file “student”. The record should be deleted on the
4
basis of student number.
ANS:

141 Write a menu driven program to do the following option on binary file “Student”. The program should implement
through list which contains student number, student name and marks.
Student Menu
------------------
1) Add New Student
4
2) Display student details
3) Search student
4) Update a Record
5) Delete a Record
6) Save & Quit
ANS:
142 Write a program to count no. of records in csv file and display the records in tabular form.

Admno, Name, Eng, Hindi, Maths, Sci, Ssc


4
1101 Tejas 80 85 90 90 75

1102 Swati 90 85 95 94 86
1103 Sam 90 80 94 96 80

1104 Imran 75 76 64 85 70

1105 Heena 85 80 80

ANS:

143 Write a function AverageColumn() which accepts csv file as parameter. It will print sum and average of each row.
For example if marks.csv contain
50,60,70,80,90
70,60,50,60,80 4
50,60,70,80,90
Then OUTPUT will be
Sum is : 350.0 Average is : 116.66666666666667
Sum is : 320.0 Average is : 106.66666666666667
Sum is : 350.0 Average is : 175.0

ANS:

144 Krishna is confused in Python code given below. Please help him to answer the following questions. 5
(a) Which line in the above code check for capital letter? (b) Which
line in the above code read the file “story. txt”? (c) Which line in the above code does not affect the execution of
program? (d) Which line is the above code coverts capital letter to small letter? (e) Which line is the above code
opens the file in write mode? (f) Which line is the above code saves the data? (g) Which line(s) is/are the part of
selection statement. (h) Which line(s) is/are used to close story1.txt?

ANS: (a) Line 6 (b) Line 4 (c) Line 10 (d) Line 7 (e) Line 2 (f) Line 13 (g) Line 6, Line 8 and Line 11 (h) Line 15

145 Aarti is new in python data-handling. Please help her to count the number of lines which begins with ‘W’ or ‘w’ in 4
poem.txt. (a) # Line 1 : To open file POEM.txt in read mode (b) # Line
2 : To check first character of every line is ‘W’ or ‘w’. (c) # Line 3 : To increase the value of count by 1. (d) # Line 4 :
To call the function count_poem.

ANS: (a) file1 = open("POEM.TXT","r")

(b) r1[0]=='W' or r1[0]=='w':

(c) count=count+1 (d) count_Poem()

146

4
Mohan has written the following code: (a) What will be the output? (i) It will
display first 20 characters. (ii) It will display 20th character and onwards. (iii) It will display first 20 bytes.
(iv) It will display content at 20th byte. (b) Meenu, Mohan's friend has written the following Python
code. What will be the output? (i) True (ii) False (iii)
None (iv) Error (c) The read() method return ____________. (i) str (ii) list (iii)
tuple (iv) None of these (d) The readline() method returns ______________. (e) The
readlines() method returns _______________.

ANS: (a) (iii) It will display first 20 bytes. (b) (i) True

(c) (i) str

(d) str (e) list

147 Mr. Iqbal is a programmer, who has recently joined the company and given a task to write a python code to perform
the following binary file operations with the help of two user defined functions/modules:

(a) Add() to create a binary file called school.dat containing student information – roll number, name,age and
marks of English, Maths and Science(out of 100) of each student. 5

(b) Display() to display the information of all students. He has succeeded in writing partial code and has missed
out certain statements, so he has left certain queries in comment lines. You as an expert of Python have to provide
the missing statements.
(a) Write the
statement to import module. (b) Write the statement to append the record in binary. (c) Write the statement to
specify object. (d) Write the statement to store data in st. (e) Statement to close the five object.

ANS: (a) import (b) ab (c) file (d) load (e) close()

148 Mr. Mathew is a programmer, who has recently joined the company and given a task to write a python code to
perform update operation in binary file (stud.dat) which contain admno (Admission No) and fee(Fee paid by
student). 5
He has succeeded in writing partial code and has missed out certain statements, You as an expert of Python have
to provide the missing statements.
(a) # statement 1 to import
module/package (b) # statement 2 to open binary file. (c) # statement 3 to store
file pointer position (d) # statement 4 to place the file pointer at specified
position (e) # statement 5 to store the data. (f) Which of the following commands is used to
write the list LST into the binary file (FILE is file object)? (i) pickle.write(LST,FILE) (ii)
pickle.write(FILE, LST) (iii) pickle.dump(LST,FILE) (iv) FILE=pickle.dump(LIST)

ANS: (a) import pickle (b) stud.dat

(c) file.tell()
(d) file.seek(pos) (e) pickle.dump(st,file) (f) (iii) pickle.dump(LST,FILE)

149 You are a student in CBSE School. Teacher has given a task to write a python code to perform the following binary
file operations with the help of two user defined functions/modules:
(a) addrecord() to create a binary file called school.dat containing student information (in list data-type) – student 5
number, name marks (out of 100) of each student.
(b) search() to display name and marks of the student by asking the student number form the user. You need to
write the code in the missing statement (Fill in the blank)
Write the statements for the following: (a) #
statement 1 to declare the data-type (b) # statement 2 to store all records in stu (c)
ANS: (a) Statement 1 : student = [] (b) Statement 2 : stu = pickle.load(f)
(c) Statement 3 : student.append(s)

(d) Statement 4 : wb (e) Statement 5 : if i[0] == r: (f) Statement 6 : break

150 Dhruv Kumar of class 12 is writing a program to create a CSV file “Teacher.csv” which will store the teacher
information entered by user. He has written the following code. As a programmer, help him to successfully execute
the given task. Write appropriate statement / function/ code against fill ups.

ANS: (a) Line 1 : import csv


(b) Line 2 with open("LAPS_Teacher12.csv" , "a", newline="") as file:

(c) Line 3 : Write = csv.writer(file) (d) LST.append([ID1,Name1,Subject]) (e) Write.writerow(LST)


151 Krishna of class 12 is writing a program to read the details of Sports performance and store in the csv file
“games.csv” delimited with a tab character. As a programmer, help him to achieve the task.

(a) Line 1 : Name the module he should import. (b) Line 2


: To create an object to enable to write in the csv file. (c) Line 3 : To store the data in list (d) Line 4 : To
write a record. (e) Line 5 : To close the file.

ANS: (a) Line 1 : Import csv (b) Line 2 : csv.writer

(c) Line 3 : rec=[sport,comp,prize]

(d) Line 4 : wobl.writerow(rec) (e) Line 5 : f.close()

152 Krishna is confused in Python code given below. Please help him to answer the following questions.

def TRANSFER(): # Line 1 5


file1=open("story.txt","r") # Line 2 file2=open("story1.txt","w") # Line 3
str1=file1.read() # Line 4 for i in str1 : # Line 5 if
i.isupper(): # Line 6 i=i.lower() # Line 7 elif i.islower():
# Line 8 i=i.upper() # Line 9 # Line
10 else : # Line 11 i=i # Line 12
file2.write(i) # Line 13 file1.close() # Line 14 file2.close() # Line
15 (a) Which line in the above code check for capital letter? (b) Which line in the above code read the
file "story.txt"? (c) Which line in the above code does not affect the execution of program? (d) Which
line is the above code coverts capital letter to small letter? (e) Which line is the above code opens the file in
write mode? (f) Which line is the above code saves the data? (g) Which line(s) is/are the part of selection
statement. (h) Which line(s) is/are used to close story1.txt?

ANS: (a) Line 6 (b) Line 4 (c) Line 10 (d) Line 7

(e) Line 2

(f) Line 13 (g) Line 6, Line 8 and Line 11 (h) Line 15

153 Aarti is new in python data-handling. Please help her to count the number of lines which begins with 'W' or 'w' in
poem.txt. POEM.txt This is my BOOk. Where is wish yours? My BOOK is
lying on the table. whom do we concern? def count_Poem(): file1 =
open("____________","_______") # Line 1 str1=file1.readlines() count=0 for r1
in str1: print(r1) if _________________ : # Line
5
2 _______________ # Line 3 print(count) file1.close()
_______________ # Line 4 (a) # Line 1 : To open
file POEM.txt in read mode (b) # Line 2 : To check first character of every line is 'W' or 'w'.
(c) # Line 3 : To increase the value of count by 1. (d) # Line 4 : To call the
function count_poem.

ANS: (a) file1 = open("POEM.TXT","r") (b) r1[0]=='W' or r1[0]=='w':


(c) count=count+1
(d) count_Poem()

154 Mohan has written the following code:

file1 = open("POEM.TXT","r")

str1=file1.read(20) print(str1) file1.close() (a) What will be the


output? (b) Meenu, Mohan's friend has written the following Python code.
5
f = None for i in range (5): with open("LAPS_W.txt", "w") as f:
if i > 2: break print(f.closed)
What will be the output? (c) The read() method return ____________.
(d) The readline() method returns ______________. (e) The readlines()
method returns _______________.

ANS: (a) It will display first 20 bytes. (b) True (c) str

(d) str

(e) list

155 You are a student in CBSE School. Teacher has given a task to write a python code to perform the following binary
file operations with the help of two user defined functions/modules:

(a) addrecord() to create a binary file called school.dat containing student information (in list
data-type) – student number, name marks (out of 100) of each student.

(b) search() to display name and marks of the student by asking the student number form 5
the user. You need to write the code in the missing statement (Fill in the blank) import pickle
def addrecord(): student=___________ f=open("student.dat","rb+")
stu=pickle._________(f) for i in stu: student.append(i)
f.close() ch='y' while ch=='y': stno=int(input("Enter
student number")) sname=input("Enter Name")
marks=int(input("Enter Marks")) s=[stno,sname,marks]
student.____________(s) ch=input("Want to add more(y/n) ?")
f=open("student.dat","________") pickle.dump(student,f) f.close()
def search(): f=open("student","rb") stu=pickle.load(f)
found=0 r=int(input("Enter the student number to be search")) for i in stu:
if i[0]==________: print("Record Found")
print(i[1],":",i[2]) found=1 ___________ if found==0: print("No record
found") f.close() Write the statements for the following: (a) # statement 1 to declare
the data-type (b) # statement 2 to store all records in stu (c) # Statement 3 function to insert
data at end. (d) # statement 4 to save the data (e) # Statement 5 to search for student
number.

ANS: (a) Statement 1 : student = [] (b) Statement 2 : stu = pickle.load(f)

(c) Statement 3 : student.append(s)

(d) Statement 4 : wb (e) Statement 5 : if i[0] == r: (f) Statement 6 : break

156 Dhruv Kumar of class 12 is writing a program to create a CSV file "Teacher.csv" which will store the teacher
information entered by user. He has written the following code. As a programmer, help him to successfully execute
the given task. Write appropriate statement / function/ code against fill ups.

import ___________

with open("Teacher.csv" , "____________", newline="") Write = 5


csv.__________(file) while True: LST=[]
ID1=int(input("Enter ID")) Name1 = input("Enter name ") Subject=
input("Subject") LST._____________([ID1,Name1,Subject])
Write.___________(LST) ch=input("Add more (y/n)? ")
if ch=='n' or ch=='N': break file.close() Write the statements
to fill the following: (a) # Line 1 (b) # Line 2 (c) # Line 3
(d) # Line 4 (e) # Line 5

ANS: (a) Line 1 : import csv

(b) Line 2 with open("LAPS_Teacher12.csv" , "a", newline="") as file:

(c) Line 3 : Write = csv.writer(file) (d) LST.append([ID1,Name1,Subject]) (e) Write.writerow(LST)

157 Krishna of class 12 is writing a program to read the details of Sports performance and store in the csv file
"games.csv" delimited with a tab character. As a programmer, help him to achieve the task.

import ___________ # Line 1

f = open(“gamess.csv”,”a”) sobj = csv.______________ (f, delimiter = ‘t’) # Line 2


sobj.writerow( [‘Games’, ‘Competitions’, ‘Prizes’] ) ans = ‘y’ i=1 while ans ==
‘y’: print(“Record :”, i) game = input(“Game Name :”) comp = 5
int(input(“No. of participitants :”)) prize = int(input(“Prizes:”)) rec =
____________________ # Line 3 sobj.______________ (rec) # Line 4 i += 1
ans = input(“Do u want to continue ? (y/n) :”) f.___________ # Line 5
(a) Line 1 : Name the module he should import. (b) Line 2 : To create an object to
enable to write in the csv file. (c) Line 3 : To store the data in list (d) Line 4
: To write a record. (e) Line 5 : To close the file.

ANS: (a) Line 1 : Import csv (b) Line 2 : csv.writer

(c) Line 3 : rec=[sport,comp,prize]

(d) Line 4 : wobl.writerow(rec) (e) Line 5 : f.close()

You might also like