You are on page 1of 26

CHAPTER – 4FILE HANDLING

[TEXT FILE, BINARY FILE AND CSV FILE]

ASSERTION & REASONING


1. A: A file is a bunch of bytes.
R: Byte is a unit of memory
2. A: File created by notepad cannot be access in python
program.
R: A text file can be created by Notepad.
3. A: The full name of a file or a directory is called Absolute
path.
R: relative path is relative to current working directory
4. A: The relative paths are relative to current working
directory.
R: The relative path for a file always remains same even
after
changing the directory.
5. A: When you open a file for writing, if the file does not
exist,
an error occurs.
R: When you open a file for writing, if the file exists, the
existing file is overwritten with the new file.
6. A: Text file stores information in ASCII or unicode
characters.
R: In text file, there is no delimiter for a line.
7. A: File can be opened in append mode.
R: In append mode file content does not get overwritten
and
user can append the content after existing content.
8. A: EOL character is a line terminator in text file.
R: By default, EOL Character is the new line character in
Text File.
9. A: with statement can be used to open any file, be it csv file
or binary file and while using with statement to open
any
file there is no need to close the file.
R: with statement groups all the statements related to file
handling and make sure to close the file implicitly. It
closes the file even when any error occurs during the
execution of statements in a with statement.
10. A: It's mandatory to mention file mode while opening a file
for reading.
R: By default, the file opens in read mode.
11. A: Binary file stores data in a format understand easily by
the computer hardware.
R: Computer hardware only understand the binary
language.
12. A: File can be opened using open() function and
“with open() as f:” syntax.
R: Once a file is opened it can‟t be closed
13. A: pickle.load( ) deserialise the python object
R: Deserialise object process involves conversion of
python object into string.
14. A: CSV files are used to store the data generated
by various social media platforms.
R: CSV file can be opened with MS Excel.
15. A:
d={'a':12, 'b':10}
f=open('data.dat', 'b')
f.write(d)
f.close( ) => Python object d is serialised onto file using file
object f.
R:
d={'a':12, 'b':10}
f=open('data.dat', 'wb')
pickle.dump( d,f)
f.close( ) => Python object d is serialised onto file using file
object f
16. A: If a text file already containing some text is opened in
Write mode the previous contents are overwritten.
R: When a file is opened in write mode the file pointer is
Present at the beginning position of the file.
17. A: The „with‟ block clause is used to associate a file object
to a file.
R: It is used so that at the end of the „with‟ block the file
resource is automatically closed
18. A: When we open the file in write mode the content of the
file will be erased if the file already exist.
R: Open function will create a file if does not exist, when
we reate the file both in append mode and write mode.
19. A: The readline( ) method reads one complete line from a
text file.
R: The readline( ) method reads one line at a time ending
with a newline(\n). It can also be used to read a
specified number (n) of bytes of data from a file but
maximum up to the newline character(\n)
20. A: The file access mode „a‟ is used to append the data in
the file.
R: In the access mode „a‟ the text will be appended at the
end of the existing file. If the file does not exist, Python
will create a new file and write data into it.
21. A: Python overwrites an existing file or creates a non-
existing file when we open a file with „w‟ mode .
R : 'a+' mode is used only for write operations
22. A: open() is a method of python.
R: open() method is used to open a file in Python and
it returns a file object called file handle. The file
handle is used to transfer data to and from the file by
calling the function defined in Python‟s io module.
23. A: Serialization is the process of transforming data to a
stream of bytes
R: It is also known as Picking
24. A: The The CSV File is delimited File.
R: Only Comma (,) can be use as delimiter in CSV file.
25. A: To specify a different delimiter while writing into a csv
file, delimiter argument is used with csv.writer ().
R: The CSV file can only take a comma as a delimiter
26. A: We can open a CSV file in the same way as a text file for
reading and writing data.
R: A CSV file is a text file that uses a delimiter to separate
values.
27. A: To open a CSV file employee.csv in write mode, we can
give python statement as follows:
fh=open('employee.csv‟)
R: If we try to write on a csv file that does not exist, the file
gets Created.
28. A: While writing data to csv file, we set the value of
parameter newline to "" in the open() function to
prevent blank rows.
R: EOL translation is suppressed by using newline="".
29. A: CSV (Comma Separated Values) is a file format for data
storage which looks like a text file.
R: The information is organized with one record on each
line and each
30. A: Binary file is faster than text file, so it is mostly used for
storing data.
R: Text file stores less character as compared to the binary
file.
31. A: with statement can be used to open a file and should be
preferred over other ways to open a file.
R: with statement is a block of statement that makes sure
the file is closed in case of any run-time error and
buffer is cleared to avoid data loss.
32. A: The tell method will stores/get the current location of
the
file pointer.
R: Python seek method returns the current position of the
file read/write pointer with the file.
33. A : The tell( ) method returns an integer that specifies the
current position of the file object in the file.
R: Offset can have any of the three values – 0, 1 and 2.
OBJECTIVE TYPE QUESTIONS (MCQ)
TEXT FILE
1. Anu is learning to use word processing software for the
first time. She creates a file with some text formatting
features using notepad. What type of file is she working
on?
(a) Text file (b) CSV file (c) Binary file (d) All of the
above
2. The _________ files are used to store large data such as
images, video files, audio files etc.
(a) Text (b) Binary (c) CSV (d) None of the Above
3. Which type of the file executes faster?
(a) Text File (b) CSV File (c) Binary File (d) Word
File
4. How many types of file path(s) are available in file
handling?
(a) 1 (b) 2 (c) 3 (d) 4
5. To open a file Myfile.txt for appending , we can use
(a) F=open("Myfile.txt","a")
(b) F=open(“Myfile.txt","w+")
(c) F=open(r"d:\Myfolder\Myfile.txt","w")
(d) F=open("Myfile.txt","w")
6. What is the use of File Object?
(a) File Object Serves as a link to a file
(b) File Objects are used to read and write data to the file
(c) A file Object is a reference to a file on disk
(d) All of the above
7. Another name of file object is
(a) File handle (b) File name
(c) No another name (d) File
8. In text file each line is terminated by a special character
called ?
(a) EOL (b) END (c) Full Stop (d) EOF
9. What error is returned by following statement, if file
“try.txt” does not exist?
f = open(“try.txt”)
(a) Not Found (b) File Not Found Error
(c) File Does Not Exist (d) No Error
10. Suppose content of „mytext.txt‟ file is:
"The key to success is focus on goals,not obstacles."
What will be the output of the following code?
file = open("mytext.txt","r")
txt = file.read()
print(file.read(10))
(a) The key to (b) obstacles. (c) Error (d) No Output
11. Which of the following statements is correct regarding file
access modes?
(a) In „r‟ mode, we can read and write data from/in the file.
(b) In „a‟ mode, the existing data will be over-written if the
file exists.
(c) In „w‟ mode, the data in the file is retained and new data
will be appended to the end.
(d) In „a+‟ mode, both reading and writing operations can
take place and new data is appended to the end of the
existing file.
12. Which of the following statements is used to open a text
file to add new contents at the end of the already existing
text file named „mydiary.txt‟?
(i) with open(“‟mydiary.txt”, „w‟) as fileobj:
(ii) fileobj = open(“mydiary.txt”, „a‟)
(iii) with open(“mydiary.txt”,‟a‟) as fileobj:
(iv) with open(“mydiary”, „r+‟) as fileobj:
(a) Only (i) (b) Only (ii)
(c) Both (ii) and (iii) (d) Both (i) and (iv)
13. “The information is stored in machine-readable format
and pickle module is used for reading and writing
data from/in the file.” Identify the type of file discussed in
the above lines?
(a) Text files (b) CSV files
(c) Binary file (d) All of the above
14. By default, in which mode a file open.
(a) r (b) w (c) a (d) None of the above
15. While using an open function in which mode a text file will
be created, if it does not exist already.
(a) r+ (b) w (c) Both of the above (d) None of the above
16. While using an open function in which mode a text file
will not be created, if it does not exist already.
(a) r+ (b) r (c) Both of the above (d) None of the above
17. When open a file in append mode, by default new data
can be added at the?
(a) Beginning of the file (b) End of the file
(c) At the middle of the file (d) All of the above
18. Which of the following is not a valid file access mode?
(a) a+ (b) r (c) w (d) b+
19. The _____ file mode is used when user want to write and
read data into Text file.
(a) rb (b) w+ (c) r+ (d) w
20. The _____ file mode is used when user want to append
data into Text file.
(a) rb (b) w+ (c) r+ (d) a
21. Consider the following Pyhton command:
F=open("Myfile","a")
which of the following option cannot be true?
(a) 'Myfile' can be a text file
(b) 'Myfile' can be a csv file
(c) 'Myfile' can be a binary file
(d) 'Myfile' will be created if not exist
22. Which of the following is not true for the Python command:
F=open("Story.txt",'a+')
(a) More text can be written into "Story.txt"
(b) Content of the file "Story.txt" can be read.
(c) Content of the file "Story.txt" can be modified
(d) Command generate error, if the file "Story.txt" does not
exists.
23. Which method is used to write multiple strings/lines in a
text file?
(a) write() (b) writeline()
(c) writelines() (d) writesingle()
24. Which function is used to read single line from file?
(a) readline() (b) readlines()
(c) readstatement( ) (d) readfulline()
25. The readlines() method returns
(a) String (b) A List of integers
(c) A list of characters (d) A List of Lines
26. To read 4th line from text file, which of the following
statement is true?
(a) dt = f.readlines()
print(dt[3])
(b) dt=f.read(4)
print(dt[3])
(c) dt=f.readline(4)
print(dt[3])
(d) All of these
27. Examine the given Python code and select the purpose of
the program from the following options:
F=open("Story.txt",'r+')
S=F.read()
S=S.upper()
F.seek(0)
F.write(S)
F.close()
(a) To count the upper case alphabets present in the file.
(b) To convert all alphabets into uppercase in the file.
(c) To copy only the upper case alphabets from the file.
(d) To remove all lower case alphabets from the file.
28. seek() is a method of?
(a) csv module (b) pickle module
(c) text module (d) file object
29. Examine the given Python code and select the best purpose
of the program from the given options:
F=open("Poem.txt",'r')
print(len(F.readline().split()))
F.close()
(a) To count the number of words present in the file.
(b) To count the number of lines present in the file.
(c) To count the number of characters present in the file.
(d) To count the number of words present in the first line of
the file.
30. To read the remaining lines of the file from a file object F,
we use________
(a) F.read (b) F.read() (c) F.readlines() (d) F.readline()
31. Consider the following Python Program:
F=open("Poem.txt","r")
T=F.readline()
Identify the data type of T:
(a) String(str) (b) List (c) Tuple (d) Dictionary
32. In which format does the readlines( ) function give the
output?
(a) Integer type (b) list type (c) string type (d) tuple type
33. What is the difference between r+ and w+ modes?
(a) No difference.
(b) In r+ mode, the pointer is initially placed at the
beginning
of the file and for w+, the pointer is placed at Knowledge
the end.
(c) In w+ mode, the pointer is initially placed at the
beginning of the file and for r+, the pointer is placed at
the end.
(d) Depends on the operating system.
34. Consider the file "Rhythm.txt": Power to Empower
What will be the output of the following code?
fileobj = open('forest.txt', 'r')
R1 = (fileobj.readline().split())
for word in R1:
for ch in range(len(word)-1,-1,-1):
print(word[ch],end='')
print(end='')
fileobj.close()

(a) rewoPot.rewopmE (b) rewopmE rewoPot


(c) Empower. to Power (d) Power Empower. to
35. Suppose the context of “Rhymes.txt” is
Hickory Dickory Dock
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) the*the* (c) Dock*the*clock* (d) error
36. What is the use of seek() method in files?
(a) sets the file‟s current position at the offset
(b) sets the file‟s previous position at the offset
(c) sets the file‟s current position within the file
(d) none of the mentioned
37. The syntax of seek() is: file_object.seek(offset [,
reference_point]) What is reference_point indicate?
(a) Reference_point indicates the starting position of the file
object.
(b) Reference_point indicates the ending position of the file
object.
(c) Reference_point indicates the current position of the file
object.
(d) All of the above.
38. The syntax of seek() is:file_object.seek(offset [,
reference_point]) What all values can be given as a
reference point?
(a)1 (b) 2 (c) 0 (d)All of the above
39. What happens if no arguments are passed to the seek()
method?
(a) file position is set to the start of file
(b) file position is set to the end of file
(c) file position remains unchanged
(d) results in an error
40. How do you change the file position to an offset value from
the start?
(a) fp.seek(offset, 0) (b) fp.seek(offset, 1)
(c) fp.seek(offset, 2) (d) none of the mentioned
41. Which statement is used to retrieve the current
position within the file?
(a) fp.seek() (b) fp.tell() (c) fp.loc (d) fp.pos
42. Consider the statements given below:
Fileobj = open(“Report.txt”, „r‟)
Fileobj.seek(25,0)
Choose the statement that best explains the second
statement.
(a) It will place the pointer at 25 bytes ahead of the
current file pointer position.
(b) It will place the pointer at 25 bytes behind from the
end-of file.
(c) It will place the pointer at 25 bytes from the beginning
of
the file.
(d) It returns 25 characters from the 0th index.
43. Assume you are reading from a text file from the
beginning and you have read 10 characters. Now you
want to start reading from the 50th character from the
beginning. Which function will you use to do the same?
(a) seek(50,1) (b) seek(50,2)
(c) seek(40,0) (d) seek(50,0)
44. Write the output of the following:
f=open("test.txt","w+")
f.write("File-Handling")
f.seek(0)
a=f.read(5)
print(a)
(a) File(b) File (c) File-H (d) No Output
45. Which of the following functions transfer the data to file
Before closing the file?
(a) flush() (b) close() (c) open() (d) fflush()
46. Write the output of the following:
f=open("test.txt","w+")
f.write("FileHandling")
f.seek(0)
a=f.read(-1)
print(a)
(a) File (b) Handling
(c) File Handling (d) No Output
47. A text file is opened using the statement f =
open(„story.txt‟). The file has a total of 10 lines. Which of
the following options will be true if statement 1 and
statement 2 are executed in order.
Statement 1: L1 = f.readline( )
Statement 2: L2 = f.readlines( )
(a) L1 will be a list with one element and L2 will be list with
9 elements.
(b) L1 will be a string and L2 will be a list with 10
elements.
(c) L1 will be a string and L2 will be a list with 9 elements.
(d) L1 will be a list with 10 elements and L2 will be an
empty list.
48. Consider the following directory structure:

There are three directories under root directory „Admin‟.


The current working directory is Final. Identify the relative
path name for file „Result1.xlsx‟.
(a) .\Result1.xlsx
(b) Admin\Final\First Term\Result1.xlsx
(c) ..\First Term\Result1.xlsx
(d) First Term\Result1.xlsx
BINARY FILE
49. What is Binary File ?
(a) These files cannot be read by humans directly.
(b) No delimiter for a line
(c) Processing of file is faster than text file
(d) All
50. A Binary file stores information in the form of ______ .
(a) A stream of bytes
(b) A stream of ASCII characters
(c) A stream of UNICODE characters
(d) All of the above
51. What are the examples of Binary file in Python?
(a) .jpeg (b) .gif (c) .bmp (d) All of the above
52. Which module is needed to be imported to work with
binary file?
(a) csv module (b) random module
(c) binary module (d) pickle module
53. The process of converting the structure to a byte stream
before writing to the file is known as ______.
(a) Pickling (b) Unpickling (c) Conversion (d) Changing
54. Name the Python module need to be imported to invoke the
function load()?
(a) csv (b) pickle (c) sql (d) binary
55. Which of the following is not a correct statement for
binary files?
(a) Easy for carrying data into buffer.
(b) Much faster than other file systems.
(c) Characters translation is not required
(d) Every line ends with new line character „\n‟
56. Which of the following file mode will refer to the BINARY
mode?
(a) binary (b) b (c) bin (d) w
57. Which file mode is invalid?
(a) ab (b) rb+ (c) wb (d) rw
58. Which file mode is valid?
(a) b+ (b) rb+ (c) rw+ (d) rw
59. Which command is used to open a binary file in Python in
append mode?
(a) F = open("Data.dat","ab") (b) F = open("Data.dat",
"wb")
(c) F = open("Data.dat", "rb") (d) None of the Above
60. Which operations can be performed in Python using "rb+"
mode?
(a) Read (b) Write
(c) Append (d) Both Read and Write
61. Which operations can be performed in Python using
"wb+" mode?
(a) Read (b) Write
(c) Append (d) Both Read and Write
62. When we open a Binary file in append mode , by default
new data can be added at the?
(a) Beginning of the file (b) End of the file
(c) At the middle of the file (d) All of the above
63. Which of the following file mode open a file for reading and
writing both in the binary file?
(a) r (b) rb (c) rb+ (d) rwb
64. To open a file c:\scores.dat in binary for reading, we use__:
(a) infile = open("c:\scores.txt", "r")
(b) infile = open("c:\\scores.dat","rb")
(c) infile = open(file = "c:\scores.txt", "r")
(d) infile = open(file = "c:\\scores.txt”, "r")
65. Which function is used to write data in binary mode?
(a) write (b) writelines (c) pickle (d) dump
66. Which function is used to read data in binary mode?
(a) read (b) load (c) pickle (d) dump
67. The method used to serialise the python objects for writing
data in binary file
(a) dump( ) (b) open( ) (c) write( ) (d) serialise( )
68. The method used to unpickling the data from a binary file
(a) unpickle( ) (b) load( ) (c) deserialise( ) (d) read( )
69. Which of the following functions can accept more than
one positional argument?
(a) pickle.load( ) (b) pickle.dump( )
(c) pickle.loads( ) (d) None of these
70. Fill in the blank in the given code :
import pickle
f = open("data.dat", "wb")
L = [1, 2, 3]
pickle._______
f.close()
(a) dump(L,f) (b) dump(f,L) (c) load(L,f) (d) load(f,L)
71. Raja is working on a binary file and he wants to write
data from a list to a binary file. Consider list object as l1,
binary file "sum_list.dat", and file object as f. Which of
the following can be the correct statement for her?
(a) f = open(„sum_list‟,‟wb‟); pickle.dump(l1,f)
(b) f = open(„sum_list‟,‟rb‟); l1=pickle.dump(f)
(c) f = open(„sum_list‟,‟wb‟); pickle.load(l1,f)
(d) f = open(„sum_list‟,‟rb‟); l1=pickle.load(f)
72. Find output of following code
import pickle
fileobject=open(„data.dat‟ , „wb‟)
L=[3,4,5,9]
pickle.dump(L, fileobject)
fileobject.close( )
fileobject=open(„data.dat‟ , „rb‟)
print( pickle.load(fileobject)[1]*2)
fileobject.close( )
(a) [3, 4, 5, 9 ] (b) [6,8,10,18] (c) 6 (d) 8
73. ____ function return the current position of the file pointer.
(a) tell() (b) seek()
(c) both A and B (d) None of the above
74. f.seek(10,0) will move 10 bytes forward from _______.
(a) beginning (b) End
(c) Current (d) None of the above
75. Which statement will move file pointer 10 bytes backward
from end position.
(a) F.seek(-10,2) (b) F.seek(10,2)
(c) F.seek(-10,1) (d) None of the above
76. Aman opened the file “myfile.dat” by using the following
syntax. His friend told him few advantages of the given
syntax. Help him to identify the correct advantage.
with open("myfile.dat", 'ab+') as fobj:
(a) In case the user forgets to close the file explicitly the file
will closed automatically.
(b) File handle will always be present in the beginning of
the
file even in append mode.
(c) File will be processed faster
(d) None of the above.
CSV FILE
77. Which of the following is tasks cannot be done or difficult
with CSV module?
(a) Storing data in tabular form (b) Finding data uniquely
(c) Saving data permanently (d) All of these
78. Which is the correct way to import a csv module?
(a) import csv (b) from csv import *
(c) None of the above (d) Both A & B
79. How many delimiters we can use in CSV file?
(a) 1 (b) 3 (c) 4 (d) 6
80. CSV files are Comma Separated Values saved as a ______
(a) Text file (b) Binary File
(c) MySQL table (d) Random file
81. In regards to separated value in files such as .csv and .tsv,
what is the delimiter?
(a) Any character such as the comma (,) or tab ;) used to
Separate the column data.
(b) Delimiters are not used
(c) Only the comma (,) character is used in the file
(d) Any character such as the comma (,) or tab ;) used to
separate the row data.
82. Which of the following statement(s) are true for csv files?
(a) Existing file is overwritten with the new file if already
exist.
(b) If the file does not exist, a new file is created for writing
purpose.
(c) When you open a file for reading, if the file does not
exist, an error occurs.
(d) All of the above.
83. Which of the following is a function of csv module?
(a) writerrow() (b) reading() (c) writing() (d)
readline()
84. The writer() function of csv module has how many
mandatory parameters?
(a) 4 (b) 3 (c) 2 (d) 1
85. To read the entire content of the CSV file as a nested list
from a file object infile, we use __________ command.
(a) infile.read() (b) infile.reader()
(c) csv.reader(infile) (d) infile.readlines()
86. Which of the following is not a valid mode to open CSV file?
(a) a (b) w (c) r (d) ab
87. Which of the following Python statement is used to read
the entire content of the CSV file as a nested list from a file
object infile?
(a) infile.read() (b) infile.reader()
(c) csv.reader(infile) (d) infile.readlines()
88. When iterating over an object returned from csv.reader(),
what is returned with each iteration? For example, given
the following code block that assumes csv_reader is an
object
returned from csv.reader(), what would be printed to the
console with each iteration?
for item in csv_reader:
print(i)
(a) The individual value data that is separated by the
delimiter.
(b) The row data as a list.
(c) The column data as a list.
(d) The full line of the file as a string.
89. Read following statement about features of CSV file and
select which statement is TRUE?
S1: Only database can support import/export to
CSV format
S2: CSV file can be created and edited using any
text editor
S3: All the columns of CSV file can be separated by
comma only
(a) S1 and S2 (b) S2 and S3 (c) S2 (d) S3
90. The command used to skip a row in a CSV file is
(a) next() (b) skip() (c) omit() (d) bounce()
91. Which of the following parameter needs to be added with
open function to avoid blank row followed by each row in
the CSV file?
(a) quotechar (b) quoting (c) newline (d) skiprow
92. EOL character used in windows operating system in CSV
files is: (a) \r\n (b) \n (c) \r (d) \0
93. To write data into CSV from python console, which of the
following function is correct?
a) csv.write(file) b) csv.writer(file)
c) csv.Write(file) d) csv.writerow()
94. What is the output of the following program?
import csv
d=csv.reader(open('city.csv'))
for row in d:
print(row)
break
If the file called city.csv contains the following details
Bhubaneshwar, Kolkata
Guwahati, Silchar
(a) Guwahati, Silchar
(b) Bhubaneshwar, Kolkata
(c) Bhubaneshwar, Kolkata
Guwahati, Silchar
(d) Bhubaneshwar Guwahati
3 – MARKS (TEXT FILE)
1. Write a method in Python to read lines from a text file
INDIA.TXT, to find and display the occurrence of the word
'India'.
2. Write a Python function which reads a text file “poem.txt”
and prints the number of vowels in each line of that file,
separately.
3. Write a method/function BIGLINES() in Python to read
lines from a text file CONTENT.TXT, and display those
lines, which are bigger than 20 characters.
4. Write a function COUNTTEXT( ), which reads a text file
Book.txt and displays all the words of the file whose length
is more than 3 or those which start with „A‟ or „a‟ . in the
form of a list. For example, if the Book.txt file contains
India is my country. They are studying.
then the output should be: [“India”, “country”, “They”,
“are”, “studying”]
5. Write a Python program that writes the reverse of each line
in “input.txt” to another text file “output.txt”. Eg: if the
content of input.txt is:
The plates will still shift
and the clouds will still spew.
The content of “output.txt” should be:
tfihs llits lliw setalp ehT
.weps llits lliw sduolc eht dna
6. Write a function named COUNT_CHAR() in python to count
and display number of times the arithmetic operators
(+,-,*,/) appears in the file “Math.txt” .
Example:
Solve the following:
1.(A+B)*C/D
2.(A-B)*(A+B)/D-(E/F)
3. A+B+C/D*(E/F)
The function COUNT_CHAR() must display the output as
Number of „+‟ sign is 4 Number of „-„ sign is 2
Number of „*‟ sign is 3 Number of „/‟ sign is 5
7. Write a function V_COUNT() to read each line from the text
file and count number of lines begins and ends with any
vowel.
8. Write a user-defined function named Count() that will read
the contents of text file named“Report.txt” and count the
number of lines which starts with either "I" or "M".
E.g. In the following paragraph, there are 2 lines starting
with "I" or "M".
9. Write a function/method DISPLAYWORDS( ) in python to
read lines from a text file STORY.TXT and display those
words, which are less than 4 characters.
10. Write a function stats( ) that accepts a filename and
reports the file‟s longest line.
11. Write a function countdigits() in Python, which should read
each character of a text file “marks.txt”, count the number
of digits and display the file content and the number of
digits.
Example: If the “marks.txt” contents are as follows:
Harikaran:40,Atheeswaran:35,Dahrshini:30,Jahnavi:48
The output of the function should be:
('Total number of digits in the file:', 8)
12. Write a function in Python to count the number of lines in
a text file „STORY.TXT‟which is starting with an alphabet
„A‟.
13. Write a method SHOWLINES() in Python to read lines from
text file TESTFILE.TXT„ and display the lines which do not
contain 'ke'.
14. Write a function RainCount() in Python, which should read
the content ofa text file ―TESTFILE.TXT‖ and then count
and display the count of occurrenceof word RAIN (case-
insensitive) in the file.
Example: If the file content is as follows:
It rained yesterday
It might rain today
I wish it rains tomorrow too
I love Rain
The RainCount() function should display the output as:
Rain – 2
15. Define a function SHOWWORD () in python to read lines
from a text file STORY.TXT, anddisplay those words, whose
length is less than 5.
16. Write a user defined function in python that displays the
number of lines starting with 'H' in the filepara.txt
17. Write a function in Python to print those words which
contains letter „S‟ or „s‟ anywhere in the word in text file
“STORY.txt”
18. Write a function COUNTLINES( ) which reads a text file
STORY.TXT and then count anddisplay the number of the
lines which starts and ends with same letter irrespective of
itscase.
BINARY FILE
1. A binary file “STUDENT.DAT” has structure
(admission_number, Name, Percentage). Write afunction
countrec() in Python that would read contents of the file
“STUDENT.DAT” anddisplay the details of those students
whose percentage is above 75. Also display number
ofstudents scoring above 75%
2. A binary file “Book.dat” has structure:
[BookNo, Book_Name, Author,Price].
i. Write a user defined function CreateFile() to input data
for
a recordand add to Book.dat.
ii. Write a function CountRec(Author) in Python which
accepts theAuthor name as parameter and count and
return number of books bythe given Author are stored
in the binary file “Book.dat”
3. A binary file “Toy.dat” has structure [TID, Toy, Status,
MRP].
i. Write a user defined function CreateFile() to input data
for
a record and add to "Toy.dat"
ii. Write a function OnOffer() in Python to display the detail
of those Toys, which has status as “ON OFFER” from
"Toy.dat" file.
4. Considering the following definition of dictionary
MULTIPLEX, write a method in python to search and
display all the content in a pickled file CINEMA.DAT,
where MTYPE key of the dictionary is matching with the
value "Comedy".
MULTIPLEX = {'MNO': _____, 'MNAME": _____, 'MTYPE':
_____}
5. As a Python expert, help to Vaishnavi to complete the
followingcode based on the requirement given above:
import ______________ #Statement 1
defshift_contact( ):
fin = open(“phonebook.dat”,‟rb‟)
fblock = open( ) #Statement 2
funblock = open( ___________________ ) #Statement 3
while True :
try:
rec = __________________ # Statement 4
if rec*“blocked”+ == „Y‟:
pickle___________________ #Statement 5
if rec*“blocked”+ == „N‟:
pickle__________________ # Statement 6
except:
break
(i) Which module should be imported in the program?
(Statement 1)
(ii) Write the correct statement required to open a
blocked.dat and unblocked.dat binary files (Statement
2 and 3)
(iii) which statement should Vaishnavi use in statement 4
to
read the data from thebinary file, phonebook.dat
(iv) which statement should Vaishnavi use in statement 5
and 6 to write data to theblocked.dat and
unblocked.dat
6. A binary file “STUDENT.DAT” has structure
(admission_number,Name, Percentage). Write a function
countrec() in Python that wouldread contents of the file
“STUDENT.DAT” and display the details ofthose students
whose percentage is above 75. Also display numberof
students scoring above 75%.
CSV FILE
1. (i) Differentiate between the writerow and writerows
function.
(ii) Write a Program in Python that defines and calls the
following user definedfunctions:
(i) add() – To accept and add data of an employee to a CSV
file„EMP.CSV‟. Each record consists of a list with
field elementsas EId, EName and ESal to store
Emp id, Empname andfurniture price
respectively.
(ii) search()- To display the records of the furniture whose
price is morethan 10000
2. HelpSumit to find theanswer of the following questions to
find the correct code for missing statements.
#Incomplete Code
import_________________________ #Statement 1
fh = open( _____ ,____ , newline=" ") #Statement 2
stuwriter = csv _________________ #Statement 3
data = []
header = [„ROLL_NO‟, „NAME‟, „CLASS‟, „SECTION‟]
data.append(header)
for i in range(5):
roll_no = int(input(“Enter Roll Number : ”))
name = input(“Enter Name : ”)
Class = input(“Class : ”)
section = input(“Enter Section : ”)
rec = [_________] #Statement 4
data.append(rec)
stuwriter._____________(data) #Statement 5
fh.close()
(i) Identify the suitable code for blank space in line marked
as Statement 1.
(ii) Identify the missing code for blank space in line
marked as Statement 2.
(iii) Choose the function name (with argument) that should
be used in the blank space of line marked as
Statement 3.
(iv) Identify the suitable code for blank space in line
marked as Statement 4.
(v) Choose the function name that should be used in the
blank space of line marked asStatement 5 to create the
desired CSV file?
3. (a) What is the use of seek() function ? Write a python
program that defines and calls the following user
defined functions.

(b) Add_book() – To read the details of the books from the


user and write into the csv file named
“book.csv”. The details of the books
stored
in a list are book_no,name,author.
Search_book() - To read the author name from the user
and display the books written by the
author.
4. (a) How to open the file using with statement? Write a
python program that defines and calls the user defined
functions given below.

(b) Add_rating() – To read product name and rating from


the user and store the same into the
csv file “product.csv”
Display() – To read the file “product.csv” and display
the products where the rating is above 10
5. Write a program in python that defines and calls the
following user defined functions:
(i) insertData() – To accept and add data of a customer and
add it to a csv file 'customerData.csv‟.
Each record should contain a list
consisting customer name, mobile no,
date of Purchase, item purchased.
(ii) frequency (name) – To accept the name of a customer
and search how many times the customer
has purchased any item. The count
and return the number.
6. Arun is a class XII student of computer science. The CCA
in-charge of his school wants to display the words form a
text files which are less than 4 characters. Do the needful
with the following python code.
def FindWords():
c=0
file=open("NewsLetter.TXT", "____ ") #Statement-1
line = file.____________ #Statement-2
word =______________ #Statement-3
for c in word:
if _____________: #Statement-4
print(c)
________________#Statement-5
FindWords()
(i) Write mode of opening the file in statement-1?
(ii) Fill in the blank in statement-2 to read the data from
the file.
(iii) Fill in the blank in statement-3 to read data word by
word.
(iv) Fill in the blank in statement-4, which display the word
having lesser than 4 characters.
(v) Fill in the blank in Statement-5 to close the file.
(vi) Which method of text file will read only one line of the
file?
7. Anu got some errors while executing the program so she
deleted those lines. As a python programmer guide her to
fill the missing statements.
_____________ # Statement 1
def modify():
e=[ ]
____________ # Statement 2
found=False
T_eno=int(input("enter employee no"))
try:
while True:
____________ # Statement 3
e=pickle.load(f)
if e[0] == T_eno:
e[2]=float(input("enter new salary"))
f.seek(pos)
__________ # Statement 4
found=True
except:
f.close()

if found==True:
print("employee record found and updated")
else:
print("employee record not found and updating not
possible")
(i) Write the statement to import the needed module.
(ii) Write the statement to open the file named “emp.bin” as
per the need of the code.
(iii) Write the statement to store the position of the file
pointer.
(iv) Complete the blank with the statement to write the
object “e” into the file.
8. Ariba Malik has been following incomplete code, which
takes a student‟s details (rollnumber, name and marks)
and writes into a binary file stu.dat using pickling.
import pickle
sturno=int(input(“Enter roll number:”))
stuname=input(“Enter name:”)
stumarks=float(input(“Enter marks:”))
stu1={"RollNo.":sturno,"Name":stuname,"Marks":stumarks}
with __________ as fh: # Fill_Line1
________________ # Fill_Line2
______________ as fin: # Fill_Line3
________________ # Fill_Line4
print(Rstu)
if Rstu[“Marks”]>=85:
print(“Eligible for merit certificate”)
else:
print(“Not eligible for merit certificate”)

(a) Complete Fill_Line1 so that the mentioned binary file is


opened for writing in fh object using a with statement.
(b) Complete Fill_Line2 so that the dictionary stu1‟s
contents are written on the file opened in step(a)
(c) Complete Fill_line3 so that the earlier created binary file
is opened for reading in a file object namely fin, using a
with statement.
(d) Complete Fill_line4 so that the contents of open file in
fin are read into a dictionary namely Rstu.
9. Ahana is writing a program to create a binary file
Employee.dat which will contain Empcode and Salary for
some employees. She has written the following code. As a
programmer, help her to successfully execute the given
task (i) Name the module she should import in Line1.
(ii) In which mode, she should open the file in Line2 to add
data into the file.
(iii) Fill in the blank in Line3 to read data from the binary
file.
(iv) Write the output she will obtain while executing Line4.

10. Aaruni Shah is learning to work with Binary files in python


using a process known as pickling/de-pickling. Her
teacher has given her the following incomplete code, which
is creating a binary file namely Mydata.dat and then opens
, reads and displays the content of the created files.
________________ #Fill_Line 1
sqlist = list()
for k in range(10):
sqlist.append(k*k)
fout = ______________ #Fill_Line2A
____________________ #Fill_Line3
fout.close()
fin = __________________ #Fill_Line2B
______________________ #Fill_Line4
fin.close()
print(“Data from file:”,mylist)
Help her complete the above code as per the instructions
given below:
(a) Complete Fill_Line1 so that the required Python library
becomes available to the program.
(b) Complete Fill_Line2A so that the above mentioned
binary file is opened for writing in the file object fout.
Similarly, complete Fill_Line2B, which will open the
same binary file for reading in the file object fin.
(c) Complete Fill_Line3 so that the list created in the code,
namely Sqlist is written in the open file.
(d) Complete Fill_Line4 so that the contents of the open file
in the file handle fin are read in a list namely mylist.
11. import pickle
sturno = int(input("Enter roll number :"))
stuname = input("Enter name:")
stumarks = float(input("Enter marks :"))
Stul = {"RNo. ":sturno, "Name": name, "Marks":stumarks}
with ______________________ as fh: # Fill_Line 1
_____________________ # Fill_Line 2
___________________ as fin: #Fill_Line 3
________________________ #Fill_Line 4
print(Rstu)
if Rstu["Marks"] >= 85:
print("Eligible for merit certificate")
else:
print("Not eligible for merit certificate")
(a) Complete Fill_Line1 so that the mentioned binary file is
opened for writing in fh object using a with statement.
(b) Complete Fill Line2 so that the dictionary Stul's
contents are written on the file opened in step (a).
(c) Complete Fill_Line3 so that the earlier created binary
file is opened for reading in a file object namely fin,
using a with statement.
(d) Complete Fill_Line4 so that the contents of open file in
fin are read into a dictionary namely Rstu
*****************************************************************

You might also like