File Handling || Multiple Choice Questions 5.
To read two characters from a file object
|| Class 12 from, the command should be:
(a) [Link](2)
(b) [Link]()
(c) [Link]()
1. To open a file c:\[Link] for reading, we (d) [Link]()
should give the statement:
(a) filel = open("c:\ [Link]", "r") 6. To read the entire contents of the file as
(b) file1 = open("c:\\ [Link]", "r") a string from a file object fobj, the
(c) file = open(file = "c:\ [Link]", "r") command should be:
(d) file1 = open(file = "c:\\s [Link]", "r")
(a) [Link](2)
(b) [Link]()
2. To open a file c:\ [Link] for writing, we (c) [Link]()
should use the statement: (d) [Link]()
(a) fobj = open("c:\[Link]", "w")
(b) fobj = open("c:\\ [Link]", "w")
(c) fobj = open(file = "c:\ [Link]", "w") 7. What will be the output of the following
(d) fobj = open(file = "c:\\ [Link]", "w") snippet?
f = None
3. To open a file c:\ [Link] for appending for i in range (5):
data, we can give the statement: with open ("[Link]", "W") as f:
(a) fobj = open("c:\\ [Link]", "a") if i > 2:
(b) fobj = open("c:\\ [Link]", "rw") break
(c) fobj = open(file = "c:\[Link]", "w") print ([Link])
(d) fobj = open(file = "c:\\ [Link]", "w")
(a) True
(b) False
(c) None
4. Which of the following statements is/are (d) Error
true?
(a) When you open a file for reading, if the 8. To read the next line of the file from a file
file does not exist, an error occurs. object fobj, we use:
(b) When you open a file for writing, if the
file does not exist, a new file is created. (a) [Link](2)
(c) When you open a file for writing, if the (b) [Link]()
file exists, the existing file is overwritten (c) [Link]()
with the new file. (d) [Link]()
(d) All of the above.
9. To read the remaining lines of the file
1
from a file object fobj, we use: (b) [Link]()
(c) [Link](sequence)
(a) [Link](2) (d) [Link]()
(b) [Link]()
(c) [Link]()
(d) [Link] 15. In file handling, what do the terms "r"
and "a" stand for?
10. The readlines() method returns: (a) read, append
(b) append, read
(a) String (iii) write, append
(b) A list of integers (d) None of the above
(c) A list of single characters
(d) A list of lines
16. Which of the following is not a valid
mode to open a file?
11. Which module is required to use the
built-in function dump( )? (a) ab
(b) rw
(a) math (c) r+
(b) flush (d) w+
(c) pickle
(d) unpickle
17. Which statement is used to change the
file position to an offset value from the
12. Which of the following functions is used start?
to write data in the binary mode?
(a) [Link](offset, 0)
(a) write (b) [Link](offset, 1)
(b) output (c) [Link](offset, 2)
(c) dump (d) None of the above
(d) send
18. The difference between r+ and w+
13. Which is/are the basic I/O (input- modes is expressed as?
output) stream(s) in file?
(a) No difference
(a) Standard Input (b) In r+ mode, the pointer is initially placed
(b) Standard Output at the beginning of the file and the pointer
(c) Standard Errors is at the end for w+
(d) All of the above (c) In w+ mode, the pointer is initially
placed at the beginning of the file and the
pointer is at the end for r+
14. Which of the following is the correct (d) Depends on the operating system
syntax of [Link]()?
(a) [Link](sequence) 19. What does CSV stand for?
2
(b) w
(a) Cursor Separated Variables (c) +
(b) Comma Separated Values (d) b
(c) Cursor Separated Values
(d) Cursor Separated Version
25. Every record in a CSV file is stored in
reader object in the form of a list using
20. Which module is used for working with which method?
CSV files in Python?
(a) writer()
(a) random (b) append()
(b) statistics (c) reader()
(c) csv (d) list()
(d) math
26. Information stored on a storage device
21. Which of the following modes is used with a specific name is called a _____.
for both writing and reading from a binary
file? (a) array
(b) dictionary
(a) wb+ (c) file
(b) w (d) tuple
(c) wb
(d) w+
27. Which of the following format of files
can be created programmatically through
22. Which statement is used to retrieve the Python to some data?
current position within the file?
(a) Data files
(a) [Link]() (b) Text files
(b) [Link]() (c) Video files
(c) [Link] (d) Binary files
(d) [Link]
28. To open a file c:\[Link] for appending
23. What happens if no arguments are data, we use
passed to the seek() method?
(a) file = open("c:\\[Link]", "a")
(a) file position is set to the start of file (b) file = open("c:\\[Link]", "rw")
(b) file position is set to the end of file (c) file = open(r"c\[Link]", "a")
(c) file position remains unchanged (d) file = open(file = "c:\[Link]", "w")
(d) results in an error (e) file = open(file = "c\\[Link]", "w")
(f) file = open("c\ [Link]")
24. Which of the following modes will refer
to binary data? 29. To read the next line of the file from a
(a) r file object infi, we use
3
(c) readall()
(a) [Link](all) (d) readchar()
(b) [Link]()
(c) [Link]()
(d) [Link]() 35. Which function is used to read single
line from file?
30. To read the remaining lines of the file (a) readline()
from a file object infi, we use (b) readlines()
(c) readstatement( )
(a) [Link](all) (d) readfulline()
(b) [Link]()
(c) [Link]()
(d) [Link]() 36. Which function is used to write all the
characters?
31. The readlines() method returns (a) write()
(b) writecharacters()
(a) str (c) writeall()
(b) a list of lines (d) writechar()
(c) a list of single characters
(d) a list of integers
37. Which function is used to write a list of
strings in a file?
32. Which of the following mode will refer
to binary data? (a) writeline()
(b) writelines()
(a) r (c) writestatement()
(b) w (d) writefullline()
(c) +
(d) b
38. Which of the following is modes of both
writing and reading in binary format in file?
33. In file handling, what does this term
means "r, a"? (a) wb+
(b) w
(a) read, append (c) wb
(b) append, read (d) w+
(c) all of the mentioned
(d) none of these
39. Which of the following is not a valid
mode to open a file?
34. Which function is used to read all the
characters? (a) ab
(b) rw
(a) read() (c) r+
(b) read characters() (d) w+
4
30. d
31. b
40. What is the difference between r+ and 32. d
w+ modes? 33. a
34. a
(a) No difference. 35. a
(b) In r+ mode, the pointer is initially placed 36. a
at the beginning of the file and for w+, the 37. b
pointer is placed at the end. 38. a
(c) In w+ mode, the pointer is initially 39. b
placed at the beginning of the file and for 40. b
r+, the pointer is placed at the end.
(d) Depends on the operating system. File Handling || Fill in the Blanks || Class
12
Answers:
1. b 1. _____ in Python are interpreted as a
2. b sequence or stream of bytes stored on
3. a
some storage media.
4. d
5. a
6. b 2. The _____ function creates a file object
7. a used to call other support methods
8. c associated with it.
9. d
10. d 3. Files in Python can be opened in one of
11. c
the three modes - _____, _____ and _____.
12. c
13. d
14. c 4. The _____ method writes a list of strings
15. a to a file.
16. b
17. a 5. The _____ method of a file object flushes
18. b any unwritten information and closes the
19. b
file object.
20. c
21. a
22. b 6. The name of the current working
23. d directory can be determined using _____
24. d method.
25. c
26. c 7. The_____ method is used to rename the
27. b, d
file or folder.
28. a, c
29. c
5
8. The _____ method is used to 21. _____ is a string method that joins all
remove/delete a file. values of each row with comma separator
in CSV.
9. A _____ file is a series of 1's and 0's,
treated as raw data and read byte-by-byte. 22. _____ object contains the number of
the current line in a CSV file.
10. The _____ statement automatically
closes the file after the processing on the 23. To end all the file contents in the form
file gets over. of a list, _____ method may be used.
11. The read() function reads data from the 24. To read all the file contents, _____
_____ of a file. method is used.
12. The pickle module produces two main 25. To force Python to write the contents of
methods called _____ and ____ for writing file buffer on to storage file, _____ method
and reading operations. may be used.
13. The readlines() returns a list of lines 26. The default file-open mode is _____
from the file till _____. mode.
14. The _____ method reads 'n' characters 27. A _____ governs the type of operations
from the file. (e.g., read/write/append) possible in the
opened file.
15. _____ function is used to force transfer
of data from buffer to file. 28. The two types of data files can be _____
files and _____ files.
16. _____ format is a text format accessible
to all applications across several platforms. 29. The other name for file object is _____.
17. _____ method is used for random 30. The _____ file mode will open a file for
access of data in a CSV file. read and write purpose.
18. _____ method of pickle module is used 31. The _____ file mode will open a file for
to write an object into binary file. write and read purpose.
19. _____ method of pickle module is used 32. To close an open file, _____ method is
to read data from a binary file. used.
20. _____ statement is given for importing 33. To read all the file contents in form of a
csv module into your program. list, ______ method is used.
6
34. To write a list in a file, _____ method 32. close()
may be used. 33. readlines()
34. writelines()
35. To force Python to write the contents of 35. flush()
file buffer on to storage file, _____ method
may be used. File Handling || True or False || Class 12
Answers:
1. Files 1. An absolute path always begins with the
2. open()
root folder.
3. read ('r'), write ('w'), append ('a')
4. writelines()
5. close() 2. It is not necessary to always create the
6. getcwd() file in the same default folder where Python
7. rename() has been installed.
8. remove()
9. binary 3. In binary file, there is no delimiter for a
10. with
line.
11. (beginning)
12. dump(), load()
13. end of file (EOF) 4. A binary file stores information in ASCII or
14. read(n) Unicode characters.
15. flush()
16. CSV 5. readline() reads the entire file at a time.
17. seek()
18. dump()
6. A close() function breaks the link of the
19. load()
file object and the file on the disk.
20. import csv
21. join()
22. line_num 7. When you open a file in read mode, the
23. readlines() given file must exist in the folder, otherwise
24. writelines() Python will raise FileNotFound error.
25. flush()
26. read
8. The default file open mode is write
27. file mode
mode.
28. text, binary
29. file handle
30. r+ 9. Opening a file in append mode erases the
31. w+ or a+ previous data.
7
10. A file mode defines the type of 20. Every record in a CSV file is stored in
operations that is to be performed on the reader object in the form of a list.
file.
21. writerow() method allows us to write a
11. A stream is defined as a sequence of list of fields to the CSV file.
characters.
22. Comma is the default delimiter for a CSV
12. readlines() function returns a list of file.
strings, each separated by "\n".
23. tell() method of Python tells us the
13. file() and open() functions have different current position within the file.
usage.
24. The offset argument to seek() method
14. Data maintained inside the file is indicates the number of bytes to be moved.
termed as "persistent” (permanent in
nature) data. 25. If the offset value is set to 2, beginning
of the file would be taken as seek position.
15. with statement ensures that all the
resources allocated to the file objects get 26. When you open a file for reading, if the
deallocated automatically. file does not exist, an error occurs.
16. CSV module can handle CSV files 27. When you open a file for writing, if the
correctly regardless of the operating system file does not exist, an error occurs.
on which the files were created.
28. When you open a file for writing, if the
17. CSV module gets automatically file exists, the existing file is overwritten
imported into your program for reading a with the new file.
CSV file.
29. The absolute paths are from the
18. The type of operation that can be topmost level of the directory structure.
performed on a file depends upon the file
mode in which it is opened. 30. The relative paths are relative to current
working directory.
19. Functions readline() and readlines() are
essentially the same. 31. The relative path for a file always
8
remains same even after changing the 15. True
directory. 16. True
17. False
32. The types of operations that can be 18. True
carried out on a file depends upon the file 19. False
mode a file is opened in. 20. True
21. True
33. If no path is given with a file name in the 22. True
file open(), then the file must exist in 23. True
current directory. 24. True
25. False
34. Functions readline() and readlines() are 26. True
essentially the same. 27. False
28. True
35. Python automatically flushes the file 29. True
buffers before closing a file with close() 30. True
function. 31. False
32. True
33. True
34. False
Answers: 35. True
File Handling || Important Questions ||
1. True Class 12 || Sumita-Arora || Preeti-Arora ||
2. False Computer Science
3. True
4. False
5. False
6. True
Q. What are the different file-processing
7. True modes supported by Python?
8. False
9. False
10. True Q. What is the difference between
11. False readline() and readlines() function?
12. True
13. False
14. True
9
Q. What is the difference between "w" and
"a" modes? Q. Write a method in Python to read lines
from a text file [Link] and display
those lines which start with the alphabet
'K'.
Q. Differentiate between file modes r+ and
w+ with respect to python.
Q. What are the advantages of saving data
in:
Q. Differentiate between file modes r+ and
rb+ with respect to Python. (i) Binary form
(ii) Text form
Q. What would be the data type of variable Q. Write a function file_long() that accepts
data in the following statements? a filename and reports the file's longest
line.
(a) data = [Link]()
(b) data = [Link](10)
(c) data = [Link]()
(d) data = [Link]() Q. Write a program to count the number of
uppercase alphabets present in a text file
"[Link]".
Q. What are the advantages of saving data
in:
Q. Write a function remove_lowercase()
(i) Binary form that accepts two file names, and copies all
(ii) Text form lines that do not start with a lowercase
letter from the first file to the second file.
Q. What is a CSV file?
Q. Write a program that reads characters
from the keyboard one by one. All lower
case characters get stored inside the file
Q. What are the advantages of CSV file LOWER, all upper case characters get stored
formats? inside the file UPPER and all other
characters get stored inside file OTHERS.
Q. Differentiate between a text file and a
binary file. Q. Reading a file line by line from the
beginning What if you want to read a file
backward? This happens when you need to
10
read log files. Write a program to read and and 40000 (both values inclusive).
display content of file from end to
beginning.
Q. Write a function countmy() in Python to
read the text file "[Link]" and count the
Q. Write a statement in Python to perform number of times "my" occurs in the file.
the following operations: For example, if the file "[Link]" contains
"This is my website. I have displayed my
• To open a text file "[Link]" in write preferences in the CHOICE section." - the
mode countmy() function should display the
• To open a text file "[Link]" in read output as: "my occurs 2 times".
mode
Q. Write a method/function
Q. Write a method in Python to write DISPLAYWORDS() in python to read lines
multiple lines of text contents into a text file from a text file [Link], and display
[Link] line. those words, which are less than 4
characters.
Q. Write a Python program to display the
size of a file after removing EOL characters, Q. Write a method in Python to read lines
leading and trailing white spaces and blank from a text file [Link] and display those
lines. lines which start with the alphabet 'P'.
Q. Write a user-defined function in Python
that displays the number of lines starting Q. Consider the file “[Link]”
with 'H' in the file Para.
Autumn Song
txt. Example, if the file contains:
Whose woods these are I think I know. Like a joy on the heart of a sorrow,
His house is in the village though; The sunset hangs on a cloud;
He will not see me stopping here A golden storm of glittering sheaves,
To watch his woods fill up with snow. Of fair and frail and fluttering leaves,
Then the line count should be 2. The wild wind blows in a cloud.
Hark to a voice that is calling
To my heart in the voice of the wind:
Q. Consider a binary file [Link] My heart is weary and sad and alone,
containing details such as empno: ename: For its dreams like the fluttering leaves have
salary (separator ':'). Write a Python gone,
function to display details of those And why should I stay behind?
employees who are earning between 20000
11
Sarojini Naidu (ii) Fill the Blank1 with statement to write
"ABC" in the file "Mydata"
Based on the above file, answer the
following question:
Q. How many file objects would you need to
(a) What would be the output of following manage the following situations:
code?
(a) To process four files sequentially.
file = open ("[Link]","r") (b) To merge two sorted files into third file.
text = [Link]()
[Link]()
for line in text :
print (line , end = ' ' ) Q. Write a program that reads a text file
print ( ) and then create a new file where each
character‘s case is inverted.
(b) Modify the program so that the lines are
printed in reverse order.
(c) Modify the code so as to output to Q. Write code to print just the last line of a
another file instead of the screen. Let your text file '[Link]'.
script overwrite the output file.
(d)Change the script of part (c) that it
append output to an existing file. Q. Create a file [Link] that stores
the details in following format:
(e) Modify the program so that each line is
printed with a line number at beginning. Name Phone
Jiving 8666000
Kriti 1010101
:
Q. Write a program using Dictionary and Obtain the details from the user.
Text files to store roman numbers and find
their equivalents.
Q. Write a program to edit the phone
number of “Arvind” infile “[Link]”.
Q. Observe the following code and answer If there is no record for “Arvind”, report
the questions that follow: error.
File = open ("Mydata","a")
_______#Blank1
[Link]() Q. Write a function in Python to count the
number of lines in a text file '[Link]'
(i) What type (Text/Binary) of file is which are starting with the alphabet 'A'.
Mydata?
12
Q. A text file contains alphanumeric text
Q. What are the different file-processing
(say [Link]). Write a program that reads this
text file and prints only the numbers or modes supported by Python?
digits from the file.
Q. Write a function in python to count the Q. What is the difference between
number of lines in a text file '[Link]'
readline() and readlines() function?
which is starting with an alphabet 'A'.
Q. Following is the structure of each record
in a data file named "[Link]". Q. What is the difference between "w" and
"a" modes?
("prod_code": value, "prod_desc": value,
"stock": value)
The values for prod_code and prod_desc
are strings and the value for stock is an Q. Differentiate between file modes r+ and
integer.
w+ with respect to python.
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. Q. Differentiate between file modes r+ and
rb+ with respect to Python.
Q. Create a CSV file "Groceries" to store
information of different items existing in a
shop. The information is to be stored w.r.t.
each item code, name, price, qty. Write a
program to accept the data from user and Q. What would be the data type of variable
store it permanently in CSV file. data in the following statements?
File Handling || Important Questions || (a) data = [Link]()
Class 12 || Sumita-Arora || Preeti-Arora || (b) data = [Link](10)
Computer Science (c) data = [Link]()
(d) data = [Link]()
13
Q. What are the advantages of saving data
in: Q. Write a function file_long() that accepts
a filename and reports the file's longest
(i) Binary form line.
(ii) Text form
Q. Write a program to count the number of
Q. What is a CSV file? uppercase alphabets present in a text file
"[Link]".
Q. What are the advantages of CSV file
formats? Q. Write a function remove_lowercase()
that accepts two file names, and copies all
lines that do not start with a lowercase
letter from the first file to the second file.
Q. Differentiate between a text file and a
binary file.
Q. Write a program that reads characters
from the keyboard one by one. All lower
Q. Write a method in Python to read lines case characters get stored inside the file
from a text file [Link] and display LOWER, all upper case characters get stored
those lines which start with the alphabet inside the file UPPER and all other
'K'. characters get stored inside file OTHERS.
Q. What are the advantages of saving data Q. Reading a file line by line from the
in: beginning What if you want to read a file
backward? This happens when you need to
(i) Binary form read log files. Write a program to read and
(ii) Text form display content of file from end to
14
beginning. Then the line count should be 2.
Q. Write a statement in Python to perform Q. Consider a binary file [Link]
the following operations: containing details such as empno: ename:
salary (separator ':'). Write a Python
• To open a text file "[Link]" in write function to display details of those
mode employees who are earning between 20000
• To open a text file "[Link]" in read and 40000 (both values inclusive).
mode
Q. Write a function countmy() in Python to
Q. Write a method in Python to write read the text file "[Link]" and count the
multiple lines of text contents into a text file number of times "my" occurs in the file.
[Link] line. For example, if the file "[Link]" contains
"This is my website. I have displayed my
preferences in the CHOICE section." - the
countmy() function should display the
Q. Write a Python program to display the output as: "my occurs 2 times".
size of a file after removing EOL characters,
leading and trailing white spaces and blank
lines.
Q. Write a method/function
DISPLAYWORDS() in python to read lines
from a text file [Link], and display
Q. Write a user-defined function in Python those words, which are less than 4
that displays the number of lines starting characters.
with 'H' in the file Para.
txt. Example, if the file contains:
Whose woods these are I think I know. Q. Write a method in Python to read lines
His house is in the village though; from a text file [Link] and display those
He will not see me stopping here lines which start with the alphabet 'P'.
To watch his woods fill up with snow.
15
(b) Modify the program so that the lines are
printed in reverse order.
Q. Consider the file “[Link]” (c) Modify the code so as to output to
another file instead of the screen. Let your
Autumn Song script overwrite the output file.
Like a joy on the heart of a sorrow, (d)Change the script of part (c) that it
The sunset hangs on a cloud; append output to an existing file.
A golden storm of glittering sheaves,
Of fair and frail and fluttering leaves, (e) Modify the program so that each line is
The wild wind blows in a cloud. printed with a line number at beginning.
Hark to a voice that is calling
To my heart in the voice of the wind:
My heart is weary and sad and alone,
For its dreams like the fluttering leaves have Q. Write a program using Dictionary and
gone, Text files to store roman numbers and find
And why should I stay behind? their equivalents.
Sarojini Naidu
Q. Observe the following code and answer
Based on the above file, answer the the questions that follow:
following question:
File = open ("Mydata","a")
(a) What would be the output of following _______#Blank1
code? [Link]()
file = open ("[Link]","r") (i) What type (Text/Binary) of file is
text = [Link]() Mydata?
[Link]() (ii) Fill the Blank1 with statement to write
for line in text : "ABC" in the file "Mydata"
print (line , end = ' ' )
print ( )
16
Q. How many file objects would you need to
manage the following situations:
Q. Write a function in Python to count the
(a) To process four files sequentially. number of lines in a text file '[Link]'
(b) To merge two sorted files into third file. which are starting with the alphabet 'A'.
Q. Write a program that reads a text file Q. A text file contains alphanumeric text
and then create a new file where each (say [Link]). Write a program that reads this
character‘s case is inverted. text file and prints only the numbers or
digits from the file.
Q. Write code to print just the last line of a
text file '[Link]'. Q. Write a function in python to count the
number of lines in a text file '[Link]'
which is starting with an alphabet 'A'.
Q. Create a file [Link] that stores
the details in following format:
Q. Following is the structure of each record
Name Phone in a data file named "[Link]".
Jiving 8666000
Kriti 1010101 ("prod_code": value, "prod_desc": value,
: "stock": value)
Obtain the details from the user. The values for prod_code and prod_desc
are strings and the value for stock is an
integer.
Q. Write a program to edit the phone Write a function in Python to update the file
number of “Arvind” infile “[Link]”. with a new value of stock. The stock and the
If there is no record for “Arvind”, report product_code, whose stock is to be
error. updated, are to be inputted during the
execution of the function.
17
Q. Create a CSV file "Groceries" to store
information of different items existing in a
shop. The information is to be stored w.r.t.
each item code, name, price, qty. Write a
program to accept the data from user and
store it permanently in CSV file.
18