File Handling
File Handling
In which of the following file modes, the existing data of file will not be
lost ?
1. 'rb'
2. ab
3. w
4. w+b
5. 'a + b'
6. wb
7. wb+
8. w+
9. r+
Answer
'rb', ab, a + b, r+
Reason —
1. 'rb' — This mode opens the file for reading in binary mode. It will
not erase the existing data and allows reading of the file.
2. 'ab' — This mode opens the file for appending in binary mode. It
will not erase the existing data but will append new data to the end
of the file.
3. 'a + b' — This mode opens the file for reading and appending. It
will not erase the existing data and allows both reading from and
appending to the file.
4. 'r+' — This mode opens the file for reading and writing. It will not
erase the existing data and allows both reading from and writing to
the file.
Question 2
What would be the data type of variable data in following statements ?
1. data = f.read()
2. data = f.read(10)
3. data = f.readline()
4. data = f.readlines()
Answer
Question 3
1. f.readline()
2. f.readline().rstrip()
3. f.readline().strip()
4. f.readline.rstrip('\n')
Answer
1. f.readline() — This statement reads a single line from the file f and
returns it as a string, including any whitespace characters at the
end of the line.
2. f.readline().rstrip() — This statement first reads a single line from
the file f, then applies the rstrip() method to remove any trailing
whitespace from the end of the line, and returns the modified line
as a string.
3. f.readline().strip() — This statement first reads a single line from
the file f, then applies the strip() method to remove any leading and
trailing whitespace from the start and end of the line, and returns
the modified line as a string.
4. f.readline.rstrip('\n') — This is not a valid syntax. The correct syntax
is f.readline().rstrip('\n'). This statement first reads a single line from
the file f, removes any trailing newline characters from the end of
the line, and returns the modified line as a string.
Checkpoint 5.2
Question 1
Answer
Question 2
Answer
Question 3
Answer
CSV (Comma Separated Values) files are delimited files that store
tabular data (data stored in rows and columns as we see in
spreadsheets or databases) where comma delimits every value. Each
line in a CSV file is a data record. Each record consists of one or more
fields, separated by commas (or the chosen delimiter).
Question 4
Name the functions used to read and write in plain text files.
Answer
1. read()
2. readline()
3. readlines()
1. write()
2. writelines()
Question 5
Answer
The functions used to read and write in binary files are load() and dump()
functions of pickle module respectively.
Question 6
Answer
The functions used to read in CSV files are as follows :
1. csv.reader()
1. csv.writer()
2. <writerobject>.writerow()
3. <writerobject>.writerows()
Question 7
1. CSV
2. TSV
Answer
Question 1
1. array
2. dictionary
3. file
4. tuple
Answer
file
Reason — A file in itself is a bunch of bytes (information) stored on
some storage device like hard-disk, thumb-drive etc with a specific
name.
Question 2
1. Data files
2. Text files
3. Video files
4. Binary files
Answer
Reason —
1. Text files — Text files are one of the most common formats for
storing data. They contain human-readable text and can be created
and manipulated using Python's built-in file handling functions like
open(), write() etc.
2. Binary files — Binary files store data in a binary format, which
means they contain sequences of bytes that may represent any
type of data, including text, images, audio, or any other type of
information. Python provides facilities for working with binary files
through modes like 'rb' (read binary) and 'wb' (write binary).
Question 3
Answer
Reason —
Question 4
To read the next line of the file from a file object infi, we use
1. infi.read(all)
2. infi.read()
3. infi.readline()
4. infi.readlines()
Answer
infi.readline()
Reason — The syntax to read a line in a file is
<filehandle>.readline(). Hence according to this syntax infi.readline()
is correct format.
Question 5
To read the remaining lines of the file from a file object infi, we use
1. infi.read(all)
2. infi.read()
3. infi.readline()
4. infi.readlines()
Answer
infi.readlines()
Question 6
1. str
2. a list of lines
3. a list of single characters
4. a list of integers
Answer
a list of lines
Reason — The readlines() method returns the entire file content in a list
where each line is one item of the list.
Question 7
1. r
2. w
3. +
4. b
Answer
Reason — When we open a file in binary mode by adding 'b' to the file
mode, it indicates that the file should be treated as a binary file.
Question 8
1. We can write content into a text file opened using 'w' mode.
2. We can write content into a text file opened using 'w+' mode.
3. We can write content into a text file opened using 'r' mode.
4. We can write content into a text file opened using 'r+' mode.
Answer
We can write content into a text file opened using 'r' mode
Reason — We can only read content into a text file opened using 'r'
mode.
Question 9
Which of the following option is the correct Python statement to read and
display the first 10 characters of a text file "Notes.txt" ?
1. F = open('Notes.txt') ; print(F.load(10))
2. F = open('Notes.txt') ; print(F.dump(10))
3. F = open('Notes.txt') ; print(F.read(10))
4. F= open('Notes.txt') ; print(F.write(10))
Answer
F = open('Notes.txt') ; print(F.read(10))
Question 10
1. F = open('Notes.txt', 'w')
2. F = open('Notes.txt., 'a')
3. F = open('Notes.txt', 'A')
4. F = open('Notes.txt', 'w+')
Answer
F = open('Notes.txt', 'A')
Question 11
1. read()
2. readcharacters()
3. readall()
4. readchar()
Answer
read()
Question 12
1. readline()
2. readlines()
3. readstatement()
4. readfullline()
Answer
readline()
Question 13
1. write()
2. writecharacters()
3. writeall()
4. writechar()
Answer
write()
1. writeline()
2. writelines()
3. writestatement()
4. writefullline()
Answer
writelines()
Question 15
1. wb+
2. w
3. wb
4. w+
Answer
wb+
Question 16
1. ab
2. rw
3. r+
4. w+
Answer
rw
Question 17
1. a+
2. r+
3. w+
4. None of these
Answer
r+
Question 18
Answer
fin = open("c:\\pat.txt", "r")
Question 19
Which of the following statements are true regarding the opening modes
of a file ?
1. When you open a file for reading, if the file does not exist, an error
occurs.
2. When you open a file for writing, if the file does not exist, an error
occurs.
3. When you open a file for reading, if the file does not exist, the
program will open an empty file.
4. When you open a file for writing, if the file does not exist, a new file
is created.
5. When you open a file for writing, if the file exists, the existing file is
overwritten with the new file.
Answer
When you open a file for reading, if the file does not exist, an error
occurs.
When you open a file for writing, if the file does not exist, a new file is
created.
When you open a file for writing, if the file exists, the existing file is
overwritten with the new file.
Reason —
1. When you open a file for writing, if the file does not exist, an error
occurs — False.
When we open a file for writing ("w" mode) and the file does not
exist, Python creates a new file.
2. When you open a file for reading, if the file does not exist, the
program will open an empty file — False.
When we try to open a file for reading ("r" mode) that does not
exist, Python raises a FileNotFoundError. It does not create an
empty file.
Question 20
Answer
Question 21
Question 22
Which of the following functions do you use to write data in the binary
format ?
1. write()
2. output()
3. dump()
4. send()
Answer
dump()
Question 23
Which of the following option is the correct usage for the tell() of a file
object ?
Reason — The tell() function returns the current byte position of file
pointer in the file as an integer.
Question 24
1. The csv module is used for reading and writing objects in binary
files.
2. The pickle module is used for reading and writing objects in binary
files.
3. The load() of the pickle module is used to read objects.
4. The dump() of the pickle module is used to write objects.
Answer
The csv module is used for reading and writing objects in binary files.
Reason — The CSV module is used for reading and writing objects in
CSV files.
Question 25
Answer
It places the file pointer at a desired offset within the file.
Question 26
1. file_object.seek(offset[, reference_point])
2. seek(offset[, reference_point])
3. seek(offset, file_object)
4. seek.file_object(offset)
Answer
file_object.seek(offset[, reference_point])
Question 1
Question 2
Question 3
The two types of data files can be text files and binary files.
Question 4
The r+ file mode will open a file for read and write purpose.
Question 5
The w+ or a+ file mode will open a file for write and read purpose.
Question 6
Question 7
To read all the file contents in the form of a list, readlines() method is
used.
Question 8
Question 9
Question 10
To read and write into binary files, pickle module of Python is used.
Question 11
The dump() method of pickle module writes data into a binary file.
Question 12
The load() method of pickle module reads data from a binary file.
Question 13
Question 14
The character that separates the values in csv files is called the
delimiter.
Question 15
Question 16
Question 17
Question 18
The file mode to open a binary file for reading as well writing is rb+.
Question 19
The file mode to open a binary file for writing as well reading is wb+.
Question 20
The file mode to open a csv file for reading as well writing is r+.
Question 21
The file mode to open a csv file for appending as well reading is a+.
Question 22
True/False Questions
Question 1
When you open a file for reading, if the file does not exist, an error
occurs.
Answer
True
Reason — When a file is opened for reading using r mode (text files) or
rb mode (binary files), if the file does not exist, Python raises an error.
Question 2
When you open a file for writing, if the file does not exist, an error
occurs.
Answer
False
Reason — When a file is opened for writing using w mode (text files) or
wb mode (binary files), if the file does not exist, file is created.
Question 3
When you open a file for writing, if the file exists, the existing file is
overwritten with the new file.
Answer
True
Reason — When we open a file for writing using w mode (text files) or
wb mode (binary files), if the file exists, Python will truncate the existing
data and overwrite in the file.
Question 4
The absolute paths are from the topmost level of the directory structure.
Answer
True
Reason — The absolute paths are from the topmost level of the directory
structure.
Question 5
Answer
True
Question 6
The relative path for a file always remains the same even after changing
the directory.
Answer
False
Reason — The relative paths are relative to current working directory.
Hence, the relative path for a file does change based on the current
working directory.
Question 7
The types of operations that can be carried out on a file depend upon the
file mode a file is opened in.
Answer
True
Question 8
If no path is given with a file name in the file open(), then the file must
exist in the current directory.
Answer
True
Question 9
False
Reason — In Python, the readline() function reads a single line from the
file and returns it as a string, while the readlines() function reads all lines
from the file and returns them as a list of strings.
Question 10
Python automatically flushes the file buffers before closing a file with
close() function.
Answer
True
Question 11
When you open a file for writing, if the file does not exist, a new file is
created.
Answer
True
Reason — When we open a file for writing using w mode (text files) or
wb mode (binary files), if the file does not exist, a new file is created.
Question 12
When you open a file for appending, if the file exists, the existing file is
overwritten with the new file.
Answer
False
Reason — When we open a file for appending using a mode (text files)
or ab mode (binary files), if the file exists, the data in the file is retained
and new data being written will be appended to the end.
Question 13
Answer
True
Question 14
Answer
True
Question 15
Answer
False
Answer
False
Question 17
Answer
False
Question 18
Answer
True
Assertion. Python is said to have broadly two types of files - binary and
text files, even when there are CSV and TSV files also.
Reason. The CSV and TSV are types of delimited text files only where
the delimiters are comma and tab respectively.
Answer
(a)
Both Assertion and Reason are true and Reason is the correct
explanation of Assertion.
Explanation
Python categorize files broadly into two types: binary files and text files.
Question 2
Assertion. The file modes "r", "w", "a" work with text files, CSV files and
TSV files alike.
Reason. The CSV and TSV are types of delimited text files only.
Answer
(a)
Both Assertion and Reason are true and Reason is the correct
explanation of Assertion.
Explanation
The file modes "r", "w", and "a" are used to specify the type of operations
that can be performed on files in Python. These modes are commonly
used with text files, CSV files, and TSV files alike because all of these
file types contain human-readable text data. CSV (Comma-Separated
Values) and TSV (Tab-Separated Values) are types of delimited text files.
Question 3
Assertion. The file modes "r", "w", "a" also reveal the type of file these
are being used with.
Reason. The binary file modes have 'b' suffix with regular file modes.
Answer
(a)
Both Assertion and Reason are true and Reason is the correct
explanation of Assertion.
Explanation
When we see file modes like "r", "w", or "a" being used in code, it often
implies operations on text files. These modes are commonly associated
with reading from, writing to, or appending text data in files. In Python,
binary file modes are distinguished from text file modes by appending 'b'
suffix to the regular file modes. For example, 'rb', 'wb', 'ab'. The presence
of the 'b' suffix indicates that the file is being opened in binary mode,
suggesting operations involving binary data.
Question 4
Answer
(b)
Both Assertion and Reason are true but Reason is not the correct
explanation of Assertion.
Explanation
Question 5
Reason. Pickling process is used to work with binary files as a binary file
works with byte-streams.
Answer
(b)
Both Assertion and Reason are true but Reason is not the correct
explanation of Assertion.
Explanation
"Pickling" is the process whereby a Python object hierarchy is converted
into a byte-stream. Pickling process is used to work with binary files as a
binary file works with byte-streams. This is because binary files can
efficiently store raw binary data, including the byte-streams produced by
pickling. The use of binary files is just one of the many possible
applications of pickling, but not the primary reason for its existence.
Question 6
Assertion. Every open file maintains a file-pointer and keeps track of its
position after every operation.
Reason. Every read and write operation takes place at the current
position of the file pointer.
Answer
(a)
Both Assertion and Reason are true and Reason is the correct
explanation of Assertion.
Explanation
Every open file maintains a file-pointer, which keeps track of the current
position within the file. This file-pointer indicates the location in the file
where the next read or write operation will occur. Every read and write
operation takes place at the current position of the file pointer. When we
perform a read operation, data is read from the file starting at the current
position of the file pointer. Similarly, when we perform a write operation,
data is written to the file starting at the current position of the file pointer.
After each operation, the file pointer is automatically updated to reflect
the new position in the file.
Question 7
Assertion. CSV (Comma Separated Values) is a file format for data
storage which looks like a text file.
Reason. The information is organized with one record on each line and
each field is separated by comma.
Answer
(a)
Both Assertion and Reason are true and Reason is the correct
explanation of Assertion.
Explanation
CSV (Comma Separated Values) is indeed a file format for data storage
that resembles a text file. CSV files are plain text files that typically use
the .csv extension and contain tabular data organized into rows and
columns. The information in CSV files is organized with one record (or
row) on each line, and each field (or column) within a record is separated
by a comma.
Question 1
Answer
If the file exists, Python will If the file exists, the data in the file is
truncate existing data and retained and new data being written will
over-write in the file. be appended to the end of the file.
Question 2
Answer
File objects are used to read and write data to a file on disk. The file
object is used to obtain a reference to the file on disk and open it for a
number of different tasks. File object is very important and useful tool as
through a file object only, a Python program can work with files stored on
hardware. All the functions that we perform on a data file are performed
through file objects.
Question 3
Answer
Question 4
Answer
The two different formats of specifying file path for opening the file
C:\Myfiles\Text1.txt in read and write mode are:
Question 5
1. csv
2. binary
3. math
4. pickle
Answer
pickle
Reason — The pickle module in Python is imported to store and retrieve
objects using the process of serialization and deserialization. It allows us
to convert Python objects into a byte stream for storage or transmission
(serialization) and to convert a byte stream into Python objects
(deserialization). This process is commonly referred to as pickling and
unpickling. The pickle module provides functions like dump() and load()
for serialization and deserialization, respectively.
Question 6
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. readrow()
2. readrows()
3. reader()
4. load()
Answer
reader()
Question 7
When a file is opened for output in write mode, what happens when
Answer
When a file is opened for output in write mode ("w" mode) in Python, the
behaviour differs depending on whether the mentioned file already exists
or not:
(i) If the mentioned file does not exist — If the file specified in the open()
function does not exist, Python will create a new file with the given
name. The file will be opened for writing, and any data written to it will be
written from the beginning of the file.
(ii) If the mentioned file does exist — If the file specified in the open()
function already exists, Python will truncate existing data and over-write
in the file. It's essential to be cautious when opening existing files in write
mode, as any existing data will be lost when the file is opened in "w"
mode.
Question 8
Answer
Here are the various text file mode constants in Python and their
meanings:
1. "r" — Opens the file for reading only. This is the default mode if no
mode is specified.
2. "w" — Opens the file for writing only.
3. "a" — Opens the file for writing, but appends new data to the end
of the file.
4. "r+" — Opens the file for both reading and writing.
5. "w+" — Opens the file for writing and reading.
6. "a+" — Opens the file for reading and appending.
Here are the various binary file mode constants in Python and their
meanings:
"rb", "wb", "ab", "rb+", "wb+", "ab+" — These modes are similar to their
corresponding text modes ("r", "w", "a", "r+", "w+", "a+"), but they operate
in binary mode.
Question 9
Answer
Question 10
When do you think text files should be preferred over binary files ?
Answer
Text files should be preferred over binary files when dealing with
human-readable data that does not require special encoding or
formatting. They are ideal for storing plain text, such as configuration
files, logs, or documents, as they are easily editable and can be viewed
using a simple text editor. Text files are also more portable and
platform-independent, making them suitable for data interchange
between different systems.
Question 11
Answer
Question 12
When a file is opened for output in append mode, what happens when
Answer
When a file is opened for output in append mode ("a" mode) in Python,
the behaviour differs depending on whether the mentioned file already
exists or not:
(i) If the mentioned file does not exist — If the file specified in the open()
function does not exist, Python will create a new file with the given
name. The file will be opened for writing, and any data written to it will be
appended to the end of the file.
(ii) If the mentioned file does exist — If the file specified in the open()
function already exists, the data in the file is retained and new data being
written will be appended to the end of the file.
Question 13
How many file objects would you need to create to manage the following
situations ? Explain.
Answer
For example :
f = open("file1.txt", "r")
# Process file 1 using f
f.close()
f = open("file2.txt", "r")
# Process file 2 using f
f.close()
f = open("file3.txt", "r")
# Process file 3 using f
f.close()
Here, we are reusing the f file object three times sequentially. We start
by opening file1 in read mode and store its file handle in file object f. We
process file1 and close it. After that, same file object f is again reused to
open file 2 in read mode and process it. Similarly, for file3 also we reuse
the same file object f.
(ii) To merge two sorted files into a third file — In this scenario, where we
need to merge two sorted files into a third file, we would need three file
objects, one for each input file and one for the output file. We would
open each input file for reading and the output file for writing. Then, we
would read data from the input files, compare the data, and write the
merged data to the output file. Finally, we would close all three files after
the merging operation is complete.
For example :
f1 = open("file1.txt", "r")
f2 = open("file2.txt", "r")
f3 = open("merged.txt", "w")
# Read line from f1
# Read line from f2
# Process lines
# Write line to f3
f1.close()
f2.close()
f3.close()
Question 14
Answer
The similarities :
The differences :
Question 15
Answer
Question 16
Why are csv files popular for data storage ?
Answer
CSV (Comma-Separated Values) files are popular for data storage due
to the following reasons:
1. Easier to create.
2. Preferred export and import format for databases and
spreadsheets.
3. Capable of storing large amount of data.
Question 17
How do you change the delimiter of a csv file while writing into it ?
Answer
To change the delimiter of a CSV file while writing into it, we can specify
the desired delimiter when creating the CSV writer object. In Python, we
can achieve this using the csv.writer() function from the csv module. By
default, the delimiter is a comma (,), but we can change it to any other
character, such as a tab (\t), semicolon (;), or pipe (|).
import csv
with open('output.csv', 'w', newline='') as csvfile:
csv_writer = csv.writer(csvfile, delimiter=';')
csv_writer.writerow(['Name', 'Age', 'City'])
csv_writer.writerow(['John', 30, 'New York'])
csv_writer.writerow(['Alice', 25, 'London'])
In this example:
1. We open the CSV file for writing using the open() function with
mode 'w'.
2. We create a CSV writer object csv_writer using csv.writer() and
specify the desired delimiter using the delimiter parameter.
3. We then use the writerow() method of the CSV writer object to
write rows to the CSV file, with each row separated by the specified
delimiter.
Question 18
When and why should you suppress the EOL translation in csv file
handling ?
Answer
Question 19
If you rename a text file's extension as .csv, will it become a csv file ?
Why/why not ?
Answer
Question 20
Differentiate between "w" and "r" file modes used in Python while
opening a data file. Illustrate the difference using suitable examples.
Answer
The "w" mode is used to open a The "r" mode is used to open a
file for writing. file for reading.
It creates a new file if the file If the file does not exist, it raises a
does not exist. FileNotFoundError.
If the file exists, Python will If the file exists, Python will open
truncate existing data and it for reading and allow to access
over-write in the file. its contents.
Example: Example:
with open("example.txt", "w") as with open("example.txt", "r") as
file: file:
print(data)
Question 21
Answer
Question 1
(a)
my_file = open('poem.txt', 'r')
my_file.read()
(b)
my_file = open('poem.txt', 'r')
my_file.read(100)
Answer
The provided code snippets (a) and (b) are similar in that they both open
the file poem.txt in read mode ('r'). However, they differ in how they read
the contents of the file:
(a) my_file.read(): This code reads the entire content of the file
poem.txt into a single string. It reads until the end of the file (EOF) is
reached.
(b) my_file.read(100): This code reads the first 100 characters from the
file poem.txt into a string. It reads up to the 100 number of characters or
until EOF is reached, whichever comes first.
Question 2
Then what outputs will be produced by both the code fragments given in
question1.
Answer
(a)
my_file = open('poemBTH.txt', 'r')
my_file.read()
Output
Explanation
This code reads the entire content of the file poemBTH.txt into a single
string. Since no specific number of characters is specified, it will read
until the end of the file (EOF) is reached.
(b)
my_file = open('poemBTH.txt', 'r')
my_file.read(100)
Output
Explanation
This code reads the first 100 characters from the file "poemBTH.txt" into
a string. It is important to note that the newline at the end of each line will
also be counted as a character.
Question 3
Consider the file poemBTH.txt given above (in previous question). What
output will be produced by following code fragment ?
obj1 = open("poemBTH.txt", "r")
s1 = obj1.readline()
s2.readline(10)
s3 = obj1.read(15)
print(s3)
print(obj1.readline())
obj1.close()
Answer
The code will result in an error because at line 3 there is a syntax error.
The correct syntax is s2 = obj1.readline().
Explanation
Output
Question 4
Write code to open file contacts.txt with shown information and print it in
following form :
Answer
Output
Question 5
Consider the file "poemBTH.txt" and predict the outputs of following code
fragments if the file has been opened in filepointer file1 with the following
code :
file1 = open("E:\\mydata\\poemBTH.txt", "r+")
(a)
print("A. Output 1")
print(file1.read())
print()
(b)
print("B. Output 2")
print(file1.readline())
print()
(c)
print("C. Output 3")
print(file1.read(9))
print()
(d)
print("D. Output 4")
print(file1.readline(9))
(e)
print("E. Output of Readlines function is")
print(file1.readlines())
print()
NOTE. Consider the code fragments in succession, i.e., code (b) follows
code (a), which means changes by code (a) remain intact when code (b)
is executing. Similarly, code (c) follows (a) and (b), and so on.
Answer
Output
A. Output 1
God made the Earth;
Man made confining countries
And their fancy-frozen boundaries.
But with unfound boundLess Love
I behold the borderLand of my India
Expanding into the World.
HaiL, mother of religions, Lotus, scenic beauty, and sages!
B. Output 2
C. Output 3
D. Output 4
After executing file1.read() in code snippet (a), the file pointer will be
moved to the end of the file (EOF) because all the content has been
read. Therefore, subsequent read operations, such as
file1.readline(), file1.read(9), and file1.readlines(), will start
from the end of the file (EOF) and will not read any further content,
resulting in empty outputs for those print statements.
Question 6
Answer
Question 7
Consider the file "contacts.csv" created in above Q. and figure out what
the following code is trying to do?
name = input("Enter name :")
file = open("contacts.csv", "r")
for line in file:
if name in line:
print(line)
Answer
The code asks the user to enter a name. It then searches for the name
in "contacts.csv" file. If found, the name and phone number are printed
as the output.
Explanation
Question 8
Consider the file poemBTH.txt and predict the output of following code
fragment. What exactly is the following code fragment doing ?
f = open("poemBTH.txt", "r")
nl = 0
for line in f:
nl += 1
print(nl)
Answer
Output
Explanation
Question 9
Write a method in Python to read the content from a text file diary.txt line
by line and display the same on screen.
Answer
def diary_content(f):
myfile = open(f, "r")
str = " "
while str:
str = myfile.readline()
print(str, end = '')
myfile.close()
diary_content("diary.txt")
Question 10
Write a method in Python to write multiple line of text contents into a text
file mylife.txt.line.
Answer
def write_to_file(file_path):
lines_to_write = ["The sun sets over the horizon.", "Birds
chirp in the morning.", "Raindrops patter on the roof.", "Leaves
rustle in the breeze."]
with open(file_path, "w") as file:
for line in lines_to_write:
file.write(line + '\n')
write_to_file("mylife.txt.line")
Question 11
Answer
Output
Dunzo
Explanation
Question 12
Answer
The code raises an error because write() function does not work in
binary file. To write an object on to a binary file dump() function of pickle
module is used.
Question 13
What is the output of the following considering the file data.csv given
below.
File data.csv contains:
Identifier;First name;Last name
901242;Riya;Verma
207074;Laura;Grey
408129;Ali;Baig
934600;Manit;Kaur
507916;Jiva;Jain
import csv
with open('C:\data.csv', 'r+') as f:
data = csv.reader(f)
for row in data:
if 'the' in row :
print(row)
Answer
Explanation
By default, csv.reader() uses a comma (,) as the delimiter to separate
values in a CSV file. But the delimiter in the file data.csv is semicolon (;),
hence the rows won't split correctly, leading to each row being treated as
a single string. When the code checks if the row contains the word 'the',
it will only print rows where 'the' appears in the entire row. Therefore, the
given code will not output anything.
Question 14(a)
Answer
import csv
f = open('attendees1.csv') #error
csv_f = csv.writer(f)
Question 14(b)
Question 15
Answer
import pickle
data = ['one', 2, [3, 4, 5]]
with open('data.dat', 'wb' : #error 1
pickle.dump(data) #error 2
1. There is a syntax error in the open() function call. The closing
parenthesis is missing in the open() function call. Also, file handle
is not mentioned.
2. The pickle.dump() function requires two arguments - the object to
be pickled and the file object to which the pickled data will be
written. However, in the provided code, the pickle.dump() function
is missing the file object argument.
Question 1
Write a program that reads a text file and creates another file that is
identical except that every sequence of consecutive blank spaces is
replaced by a single space.
Answer
Question 2
Answer
Question 3
The names contain only one word, the names and telephone numbers
are separated by white spaces. Write program to read a file and display
its contents in two columns.
Answer
Output
Arvind 7258031
Sachin 7259197
Karuna 8479939
Question 4
Write a program to count the words "to" and "the" present in a text file
"Poem.txt".
Answer
to_count = 0
the_count = 0
Output
count of 'to': 4
count of 'the': 5
Question 5
Example :
If the file content is as follows :
Updated information
As simplified by official websites.
Answer
def AMCount(file_path):
count_a = 0
count_m = 0
with open(file_path, 'r') as file:
ch = ' '
while ch:
ch = file.read(1)
ch_low = ch.lower()
if ch_low == 'a':
count_a += 1
elif ch_low == 'm':
count_m += 1
Output
A or a: 4
M or m: 2
Question 6
Answer
print(count)
Output
Question 7
Write a program that copies one file to another. Have the program read
the file names from user ?
Answer
def copy_file(file1, file2):
with open(file1, 'r') as source:
with open(file2, 'w') as destination:
destination.write(source.read())
copy_file(source_file, destination_file)
Question 8
Write a program that appends the contents of one file to another. Have
the program take the filenames from the user.
Answer
def append_file(f1, f2):
with open(f1, 'r') as source:
with open(f2, 'a') as destination:
destination.write(source.read())
append_file(source_file, destination_file)
Question 9
Answer
def display_lines(file_name):
with open(file_name, 'r') as file:
line = file.readline()
while line:
if line.strip().startswith('K'):
print(line.strip())
line = file.readline()
display_lines("MYNOTES.TXT")
Output
Question 10
Answer
def DISPLAYWORDS(file_name):
with open(file_name, 'r') as file:
for line in file:
words = line.split()
for word in words:
if len(word) < 4:
print(word)
for line in file:
words = line.split()
for word in words:
if len(word) < 4:
print(word)
DISPLAYWORDS("STORY.TXT")
Output
a
was
a
boy
Jay
He
had
a
dog
Leo
Question 11
Write a program that reads characters from the keyboard one by one. All
lower case characters get stored inside the file LOWER, all upper case
characters get stored inside the file UPPER and all other characters get
stored inside file OTHERS.
Answer
lower_file = open("LOWER.txt", 'w')
upper_file = open("UPPER.txt", 'w')
others_file = open("OTHERS.txt", 'w')
ans = 'y'
while ans == 'y':
char = input("Enter a character: ")
if char.islower():
lower_file.write(char + "\n")
elif char.isupper():
upper_file.write(char + "\n")
else:
others_file.write(char + "\n")
ans = input("Want to enter a character? (y/n): ")
lower_file.close()
upper_file.close()
others_file.close()
Output
Enter a character: e
Want to enter a character? (y/n): y
Enter a character: A
Want to enter a character? (y/n): y
Enter a character: D
Want to enter a character? (y/n): y
Enter a character: c
Want to enter a character? (y/n): y
Enter a character: 7
Want to enter a character? (y/n): y
Enter a character: @
Want to enter a character? (y/n): n
Question 12
Answer
def count_lines(file_name):
count = 0
with open(file_name, 'r') as file:
for line in file:
if line.strip().startswith('A'):
count += 1
print(count)
count_lines("LINES.TXT")
Output
3
Question 13
Answer
count = 0
with open("myfile.txt", 'r') as file:
while True:
char = file.read(1)
if char == '$' or not char:
break
count += 1
print(count)
Output
78
Question 14
Write a program that will create an object called filout for writing,
associate it with the filename STRS.txt. The code should keep on writing
strings to it as long as the user wants.
Answer
with open('STRS.txt', 'w') as filout:
ans = 'y'
while ans == 'y':
string = input("Enter a string: ")
filout.write(string + "\n")
ans = input("Want to enter more strings?(y/n)...")
Output
Question 15
Answer
import pickle
def write_member():
file = open("member.dat", 'wb')
pickle.dump(member1, file)
pickle.dump(member2, file)
file.close()
write_member()
Question 16
Answer
import pickle
def search_and_display_staff(staff_code):
found = False
try:
file = open("staff.dat", "rb")
while True:
staff_data = pickle.load(file)
if staff_data['Staffcode'] == staff_code:
print("Staffcode:", staff_data['Staffcode'])
print("Name:", staff_data['Name'])
found = True
except EOFError:
if found == False:
print("End of file reached. No such records found.")
else:
print("Search Successful")
file.close()
search_and_display_staff('S0105')
Output
Staffcode: S0105
Name: Aditya
Question 17
Answer
import pickle
def company(comp_id):
found = False
try:
file = open("COMPANY.DAT", "rb")
while True:
company_data = pickle.load(file)
if company_data['CompID'] == comp_id:
print("Company ID:", company_data['CompID'])
print("Company Name:", company_data['CName'])
print("Turnover:", company_data['Turnover'])
found = True
except EOFError:
if found == False:
print("End of file reached. No such records found.")
else:
print("Search Successful")
file.close()
company('1005')
Output
Question 18
Answer
import pickle
def search_trains():
found = False
try:
file = open("TRAIN.DAT", "rb")
while True:
trains = pickle.load(file)
if trains['To'] == "Delhi":
print("Train no: ", trains['Tno'])
print("From: ", trains['From'])
print("To: ", trains['To'])
found = True
except EOFError:
if found == False:
print("End of file reached. No such records found.")
else:
print("Search Successful")
file.close()
search_trains()
Output
Question 19
(i) Write a user defined function CreateFile() to input data for a record
and add to Book.dat.
Answer
import pickle
def CreateFile():
file = open("Book.dat", "ab")
BookNo = int(input("Enter Book Number: "))
Book_Name = input("Enter Book Name: ")
Author = input("Enter Author Name: ")
Price = float(input("Enter Price: "))
record = [BookNo, Book_Name, Author, Price]
pickle.dump(record, file)
file.close()
def CountRec(authorName):
count = 0
found = False
try:
file = open("Book.dat", "rb")
while True:
record = pickle.load(file)
if record[2] == authorName:
count += 1
found = True
except EOFError:
if found == False:
print("End of file reached. No such records found.")
else:
print("Search successful")
file.close()
return count
CreateFile()
author = input("Enter Author name to count books: ")
print("Number of books by", author, ":", CountRec(author))
Output
Question 20
Answer
def Show_words(file_name):
with open(file_name, 'r') as file:
for line in file:
words = line.strip().split()
if len(words) == 5:
print(line.strip())
Show_words('NOTES.TXT')
Output
Question 21
Write a Python program to read a given CSV file having tab delimiter.
Answer
Let "example.csv" file contain the following data:
Name Age Gender
Kavya 25 Female
Kunal 30 Male
Nisha 28 Female
import csv
Output
Question 22
Write a Python program to write a nested Python list to a csv file in one
go. After writing the CSV file read the CSV file and display the content.
Answer
import csv
def read_csv(file_name):
with open(file_name, 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
write_nested_list(nested_list, 'output.csv')
print("Content of 'output.csv':")
read_csv('output.csv')
Output
Question 23
Write a function that reads a csv file and creates another csv file with the
same content, but with a different delimiter.
Answer
import csv
def change_delimiter(input_file, output_file, input_delimiter,
output_delimiter):
with open(input_file, 'r', newline='') as f_in:
reader = csv.reader(f_in, delimiter = input_delimiter)
data = list(reader)
Contents of "modified.csv":
Product|Price|Quantity
Apple|1.99|100
Banana|0.99|150
Orange|2.49|80
Question 24
Write a function that reads a csv file and creates another csv file with the
same content except the lines beginning with 'check'.
Answer
import csv
filter('input.csv', 'output.csv')
Contents of "output.csv":
data1,30,C
data2,50,E
Question 25
Give any one point of difference between a binary file and a CSV file.
Write a Program in Python that defines and calls the following user
defined functions :
(b) search(). To display the records of the furniture whose price is more
than 10000.
Answer
The difference between a binary file and CSV file is that binary files are
used for storing complex data in a non-human-readable format and they
store data in a sequence of bytes, while CSV files are plain text files
used for storing structured tabular data in a human-readable text format.
Let the file "furdata.csv" include following data:
[1, table, 20000]
[2, chair, 12000]
[3, board, 10000]
import csv
def add():
def search():
found = False
with open('furdata.csv', mode='r') as file:
reader = csv.reader(file)
print("Records of furniture with price more than
10000:")
for row in reader:
if len(row) == 3 and float(row[2]) > 10000:
print("Furniture ID:", row[0])
print("Furniture Name:", row[1])
print("Furniture Price:", row[2])
print()
found = True
if found == False:
print("No records of furniture with price more than
10000 found")
add()
search()
Output
Enter furniture id: 9
Enter furniture name: desk
Enter furniture price: 3000
Record added successfully to 'furdata.csv'
Records of furniture with price more than 10000:
Furniture ID: 1
Furniture Name: table
Furniture Price: 20000
Furniture ID: 2
Furniture Name: chair
Furniture Price: 12000