KnowledgeBoat Logo
OPEN IN APP

Chapter 4

Data File Handling

Class 12 - Computer Science with Python Preeti Arora



Fill in the Blanks

Question 1

Files in Python are interpreted as a sequence or stream of bytes stored on some storage media.

Question 2

The open() function creates a file object used to call other support methods associated with it.

Question 3

Files in Python can be opened in one of the three modes — read ('r'), write('w') and append('a').

Question 4

The writelines() method writes a list of strings to a file.

Question 5

The close() method of a file object flushes any unwritten information and closes the file object.

Question 6

The name of the current working directory can be determined using getcwd() method.

Question 7

The rename() method is used to rename the file or folder.

Question 8

The remove() method is used to remove/delete a file.

Question 9

A binary file is a series of 1's and 0's, treated as raw data and read byte-by-byte.

Question 10

The with statement automatically closes the file after the processing on the file gets over.

Question 11

The read() function reads data from the beginning of a file.

Question 12

The pickle module produces two main methods called dump() and load() for writing and reading operations.

Question 13

The readlines() returns a list of strings from the file till end of file (EOF).

Question 14

The read(n) method reads 'n' characters from the file.

Question 15

flush() function is used to force transfer of data from buffer to file.

Question 16

CSV format is a text format accessible to all applications across several platforms.

Question 17

seek() method is used for random access of data in a CSV file.

Question 18

dump() method of pickle module is used to write an object into binary file.

Question 19

load() method of pickle module is used to read data from a binary file.

Question 20

import csv statement is given for importing csv module into your program.

Question 21

join() is a string method that joins the string with a string separator.

Question 22

line_num object contains the number of the current line in a CSV file.

Question 23

To read all the file contents in the form of a list, readlines() method is used.

Question 24

To write contents of list, tuple and sequence data type writelines() method may be used.

Question 25

To force Python to write the contents of file buffer on to storage file, flush() method may be used.

Question 26

When we work with file, buffer area is automatically associated with the file when we open it.

State True or False

Question 1

An absolute path always begins with the root folder.

Answer

True

Reason — An absolute path always starts from the root folder, which is the top-level directory in a file system.

Question 2

It is not necessary to always create the file in the same default folder where Python has been installed.

Answer

False

Reason — It is necessary to always create the file in the same default folder where Python has been installed.

Question 3

In binary file, there is no delimiter for a line.

Answer

True

Reason — There is no delimiter for a line in a binary file because binary files store data in a sequence of binary digits (bits and bytes) that represent the actual information being stored, such as numbers, images, audio, or other types of data.

Question 4

A binary file stores information in ASCII or Unicode characters.

Answer

False

Reason — Binary files store data in a sequence of binary digits (bits and bytes), not in ASCII or Unicode characters.

Question 5

readline() reads the entire file at a time.

Answer

False

Reason — The readline() function reads one line at a time from a file, starting from the current cursor position up to and including the end of the line character (\n).

Question 6

A close() function breaks the link of the file object and the file on the disk.

Answer

True

Reason — The close() function breaks the link between the file object and the file on the disk. It flushes any unwritten information and closes the file object, preventing further writing operations.

Question 7

When we open a file in read mode, the given file must exist in the folder; otherwise, Python will raise FileNotFound error.

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 will raise FileNotFound error.

Question 8

The default file open mode is write mode.

Answer

False

Reason — The default file open mode in Python is read mode ('r'). If the mode is not specified when opening a file, Python assumes it to be in read mode by default.

Question 9

Opening a file in append mode erases the previous data.

Answer

False

Reason — Opening a file in append mode 'a' for text files or 'ab' for binary files does not erase the previous data. Instead, it allows data to be added to the end of the file without overwriting or erasing existing content.

Question 10

A file mode defines the type of operations that is to be performed on the file.

Answer

True

Reason — In Python, a file mode defines the types of operations that can be performed on the file, such as reading, writing, appending, etc.

Question 11

A stream is defined as a sequence of characters.

Answer

False

Reason — A stream is defined as a sequence of bytes or bits.

Question 12

readlines() function returns a list of strings, each separated by "\n".

Answer

True

Reason — The readlines() function reads all lines from the file into a list. It starts reading from the cursor position up to the end of the file and returns a list of strings, with each string separated by the newline character '\n'.

Question 13

Data maintained inside the file is termed as "persistent" (permanent in nature) data.

Answer

True

Reason — Data maintained inside the file is termed as "persistent" data, i.e., it is permanent in nature. Python allows us to read data from and save data to external text files permanently on secondary storage media.

Question 14

'with' statement ensures that all the resources allocated to the file objects get deallocated automatically.

Answer

True

Reason — The 'with' statement ensures that all resources allocated to file objects are deallocated automatically once we stop using the file. In the case of exceptions also, we are not required to explicitly close the file using the 'with' statement.

Question 15

csv module can handle CSV files correctly regardless of the operating system on which the files were created.

Answer

True

Reason — The csv module in Python can handle CSV files correctly irrespective of the operating system on which the files were created. This module facilitates the reading and writing of tabular data in CSV format.

Question 16

csv module gets automatically imported into the program for reading a CSV file.

Answer

False

Reason — The csv module in Python needs to be explicitly imported into the program using the import csv statement before it can be used for reading CSV files. It's not automatically available.

Question 17

The type of operation that can be performed on a file depends upon the file mode in which it is opened.

Answer

True

Reason — The operations that can be carried out on a file, such as reading, writing, and appending, depend on the file mode specified during the file opening. For example, if a file is opened in read-only mode ('r'), we can only perform read operations on it, whereas if it's opened in write mode ('w'), we can only perform write operations.

Question 18

Functions readline() and readlines() are essentially the same.

Answer

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 19

Every record in a CSV file is stored in reader object in the form of a list.

Answer

True

Reason — The reader object in the csv module is an iterable that provides access to each line of a CSV file, with each line represented as a list of fields.

Question 20

writerow() method allows us to write a list of fields to the CSV file.

Answer

True

Reason — The writerow() method in the csv module allows us to write a list of fields to a CSV file.

Question 21

Comma is the default delimiter for a CSV file.

Answer

True

Reason — The comma (,) is the most popular and default delimiter for a CSV file. This means that values in the file are separated by commas by default.

Question 22

tell() method of Python tells us the current position within the file.

Answer

True

Reason — The tell() function returns the current position of file read/write pointer within the file.

Question 23

The offset argument to seek() method indicates the number of bytes to be moved.

Answer

True

Reason — In the seek() method of Python, the offset argument indicates the number of bytes by which the file read/write pointer should be moved.

Question 24

If the offset value is set to 2, beginning of the file would be taken as seek position.

Answer

False

Reason — If the offset value is set to 2, end of the file would be taken as seek position.

Multiple Choice Questions

Question 1

To open a file c:\test.txt for reading, we should give the statement:

  1. file1= open("c:\ test.txt", "r")
  2. file1 = open("c:\\ test.txt", "r")
  3. file1 = open(file = "c:\ test.txt", "r")
  4. file1 = open(file = "c:\\s test.txt", "r")

Answer

file1 = open("c:\\test.txt", "r")

Reason — The syntax for 'open()' is: <file variable>/<file object or handle> = open(file_name, access_mode). Therefore, according to this syntax, file1 = open("c:\\test.txt", "r") is the correct statement to open a file for reading. The access mode "r" indicates that the file should be opened in read mode.

Question 2

To open a file c:\test.txt for writing, we should use the statement:

  1. fobj = open("c:\test.txt", "w")
  2. fobj = open("c:\\test.txt", "w")
  3. fobj = open(file = "c:\test.txt", "w")
  4. fobj = open(file = "c:\\test.txt", "w")

Answer

fobj = open("c:\\test.txt", "w")

Reason — The syntax for 'open()' is: <file variable>/<file object or handle> = open(file_name, access_mode). Therefore, according to this syntax, fobj = open("c:\\test.txt", "w") is the correct statement to open a file for writing. The access mode "w" indicates that the file should be opened in write mode.

Question 3

To open a file c:\test.txt for appending data, we can give the statement:

  1. fobj = open("c:\\test.txt", "a")
  2. fobj = open("c:\\test.txt", "rw")
  3. fobj = open(file = "c:\test.txt", "w")
  4. fobj = open(file = "c:\\test.txt", "w")

Answer

fobj = open("c:\\test.txt", "a")

Reason — The syntax for 'open()' is: <file variable>/<file object or handle> = open(file_name, access_mode). Therefore, according to this syntax, fobj = open("c:\\test.txt", "a") is the correct statement to open a file for writing. The access mode "a" indicates that the file should be opened in append mode.

Question 4

Which of the following statements is/are true?

  1. When we open a file for reading, if the file does not exist, an error occurs.
  2. When we open a file for writing, if the file does not exist, a new file is created.
  3. When we open a file for writing, if the file exists, the existing file is overwritten with the new file.
  4. All of these.

Answer

All of these.

Reason — When we open a file for reading ('r' mode) that doesn't exist, Python raises an error (FileNotFoundError). When we open a file for writing ('w' mode) and the file doesn't exist, a new file is created with the specified name. If we open a file for writing ('w' mode) and the file already exists, the existing file is overwritten with the new file.

Question 5

To read two characters from a file object fobj, the command should be:

  1. fobj.read(2)
  2. fobj.read()
  3. fobj.readline()
  4. fobj.readlines()

Answer

fobj.read(2)

Reason — The command fobj.read(2) is used to read two characters from a file object fobj. The read() method without arguments (fobj.read()) reads the entire content of the file, while fobj.readline() reads a single line, and fobj.readlines() reads all lines and returns them as a list.

Question 6

To read the entire contents of the file as a string from a file object fobj, the command should be:

  1. fobj.read(2)
  2. fobj.read()
  3. fobj.readline()
  4. fobj.readlines()

Answer

fobj.read()

Reason — The command fobj.read() is used to read the entire contents of the file as a string from a file object fobj.

Question 7

What will be the output of the following snippet?

f = None
for i in range(5):
    with open("data.txt", "w") as f:
       if i > 2:
        break
print(f.closed)
  1. True
  2. False
  3. None
  4. Error

Answer

True

Reason — Initially, the variable f is assigned None. The code then enters a for loop that runs five times (for i in range(5)). Inside the loop, a file named "data.txt" is opened in write mode ("w") using the with statement. If the value of i is greater than 2, the loop breaks using break. After the loop breaks, the print(f.closed) statement is executed outside the with block. Since the file object f was opened within the with block, it is automatically closed when the block exits. The f.closed attribute returns True if the file is closed, which happens because of the with statement's automatic closing behavior.

Question 8

To read the next line of the file from a file object fobj, we use:

  1. fobj.read(2)
  2. fobj.read()
  3. fobj.readline()
  4. fobj.readlines()

Answer

fobj.readline()

Reason — The syntax to read a line in a file is <filehandle>.readline(). Hence according to this syntax fobj.readline() is correct format.

Question 9

To read the remaining lines of the file from a file object fobj, we use:

  1. fobj.read(2)
  2. fobj.read()
  3. fobj readline()
  4. fobj.readlines()

Answer

fobj.readlines()

Reason — The syntax to read all lines in a file is <filehandle>.readlines(). Hence according to this syntax fobj.readlines() is correct format.

Question 10

The readlines() method returns:

  1. String
  2. A list of integers
  3. A list of single characters
  4. A list of strings

Answer

A list of strings

Reason — The readlines() method reads all lines from the file into a list and returns a list of strings, where each string represents a line from the file, separated by the new line character '\n'.

Question 11

Which module is required to use the built-in function dump()?

  1. math
  2. flush
  3. pickle
  4. unpickle

Answer

pickle

Reason — The dump() function is part of the pickle module in Python. Therefore, to use the dump() function, we need to import the pickle module.

Question 12

Which of the following functions is used to write data in the binary mode?

  1. write
  2. output
  3. dump
  4. send

Answer

dump

Reason — To write an object on to a binary file opened in the write mode, we should use dump() function of pickle module as per following syntax: pickle.dump(<object-to-be-written>, <file-handle-of-open-file>).

Question 13

Which is/are the basic I/O (input-output) stream(s) in file?

  1. Standard Input
  2. Standard Output
  3. Standard Errors
  4. All of these

Answer

All of these

Reason — The basic I/O streams related to files are Standard Input (stdin), Standard Output (stdout), and Standard Error (stderr). Standard Input (stdin) is used for receiving input, Standard Output (stdout) is the stream for regular output, and Standard Error (stderr) is specifically designated for error messages and warnings.

Question 14

Which of the following is the correct syntax of file object 'fobj' to write sequence data type using writelines() function?

  1. file.writelines(sequence)
  2. fobj.writelines()
  3. fobj.writelines(sequence)
  4. fobj.writeline()

Answer

fobj.writelines(sequence)

Reason — The syntax for a file object to write sequence data using the writelines() function is fileobject.writelines(sequence). Therefore, fobj.writelines(sequence) is correct.

Question 15

In file handling, what do the terms "r" and "a" stand for?

  1. read, append
  2. append, read
  3. write, append
  4. None of these

Answer

read, append

Reason — In file handling, the term "r" stands for "read" mode, which is used when we want to read data from a file and "a" stand for "append" mode, which is used when we want to add data to the file.

Question 16

Which of the following is not a valid mode to open a file?

  1. ab
  2. rw
  3. r+
  4. w+

Answer

rw

Reason — 'rw' is not a valid mode to open file in Python.

Question 17

Which statement is used to change the file position to an offset value from the start?

  1. fp.seek(offset, 0)
  2. fp.seek(offset, 1)
  3. fp.seek(offset, 2)
  4. None of these

Answer

fp.seek(offset, 0)

Reason — The syntax for relative referencing is f.seek(offset, from_what). The statement f.seek(offset, 0) is used to change the file position to an offset value from the start, where 0 sets the reference point at the beginning of the file.

Question 18

The difference between r+ and w+ modes is expressed as?

  1. No difference
  2. In r+ mode, the pointer is initially placed at the beginning of the file and the pointer is at the end for w+
  3. In w+ mode, the pointer is initially placed at the beginning of the file and the pointer is at the end for r+
  4. Depends on the operating system

Answer

In r+ mode, the pointer is initially placed at the beginning of the file and the pointer is at the end for w+

Reason — In 'r+' mode (read and write), the pointer is initially placed at the beginning of the file. In 'w+' mode (read and write), the pointer is placed at the end of the file.

Question 19

What does CSV stand for?

  1. Cursor Separated Variables
  2. Comma Separated Values
  3. Cursor Separated Values
  4. Cursor Separated Version

Answer

Comma Separated Values

Reason — The CSV stands for "Comma Separated Values".

Question 20

Which module is used for working with CSV files in Python?

  1. random
  2. statistics
  3. csv
  4. math

Answer

csv

Reason — For working with CSV files in Python, there is an inbuilt module called csv. It is used to read and write tabular data in CSV format.

Question 21

Which of the following modes is used for both writing and reading from a binary file?

  1. wb+
  2. w
  3. wb
  4. w+

Answer

wb+

Reason — 'wb+' mode is used for both writing and reading from a binary file.

Question 22

Which statement is used to retrieve the current position within the file?

  1. fp.seek()
  2. fp.tell()
  3. fp.loc
  4. fp.pos

Answer

fp.tell()

Reason — The tell() method returns the current position of the file read/write pointer within the file. The correct syntax to use it is fp.tell(). Therefore, the correct statement used to retrieve the current position within the file is fp.tell().

Question 23

What happens if no arguments are passed to the seek() method?

  1. file position is set to the start of file
  2. file position is set to the end of file
  3. file position remains unchanged
  4. results in an error

Answer

results in an error

Reason — If no arguments are passed to the seek() method in Python, it will result in an error because the method expects at least one argument to specify the new position within the file.

Question 24

Which of the following modes will refer to binary data?

  1. r
  2. w
  3. +
  4. b

Answer

b

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 25

Every record in a CSV file is stored in reader object in the form of a list using which method?

  1. writer()
  2. append()
  3. reader()
  4. list()

Answer

reader()

Reason — The reader() function is used to store every record in a CSV file in a reader object, where each record is represented as a list.

Question 26

For storing numeric data in a text file, it needs to be converted into ............... using ............... function.

  1. integer, int()
  2. integer, float()
  3. string, int()
  4. string, str()

Answer

string, str()

Reason — For storing numeric data in a text file, it needs to be converted into a string using the 'str()' function. This is because text files store data in the form of characters, and converting numeric data to a string allows it to be written to the file as a sequence of characters.

Assertions and Reasons

Question 1

Assertion (A): The file in Python is used to store information on a named location in the secondary storage device.

Reasoning (R): In Python, files are classified as program files and data files and as per the file type store the data specific to its use and purpose.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
In Python, a file is used to store information on a named location in the secondary storage device. Files can be classified into different types such as program files and data files. Program files contain Python scripts (with .py extension), while data files store specific data relevant to their purpose. This classification helps organize and manage files based on their content and usage.

Question 2

Assertion (A): The file access mode used to add or append the data in the file is 'a'.

Reasoning (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 to it.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
The file access mode used to add or append data in the file is 'a'. In the 'a' access mode, the file pointer is at the end of the file if the file exists, and 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 to it.

Question 3

Assertion (A): The binary files are an advanced version of text files and work similar to text files.

Reasoning (R): The data in binary files are stored in the form of binary digits, 0 and 1; and is directly understood by the computer.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

A is false but R is true.

Explanation
Binary files are not an advanced version of text files but rather a different type of file. They serve different purposes and handle data differently. Text files store data as human-readable text using characters, while binary files store data using binary digits (0s and 1s), which are directly understood by computers.

Question 4

Assertion (A): To work with binary files, we need to import pickle module.

Reasoning (R): Pickle module contains two important methods for reading and writing data to binary files, i.e., load() and dump() respectively.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
To work with binary files in Python, we indeed need to import the pickle module. The pickle module is used for serializing and deserializing Python objects and contains two important methods, load() and dump(), for reading and writing data to binary files, respectively.

Question 5

Assertion (A): The close() method is used to close the file.

Reasoning (R): While closing a file, the system frees up all the resources like CPU processor time and memory allocated to it.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
The close() method in Python is used to flush any unwritten information, and close the file object, preventing further writing. While closing a file, the system frees up resources such as CPU processor time and memory that were allocated to the file.

Question 6

Assertion (A): The readline() method reads one complete line from a text file.

Reasoning (R): The readline() function 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).

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

Explanation
The readline() method in Python reads one complete line from a text file and can also be used to read a specified number (n) of bytes of data from a file up to the newline character (\n).

Question 7

Assertion (A): CSV stands for Comma Separated Values.

Reasoning (R): CSV files are common file format for transferring and storing data.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true but R is not the correct explanation of A.

Explanation
CSV stands for Comma-Separated Values. CSV file format is commonly used for transferring and storing data in a plain text format, especially when dealing with spreadsheet or database-like information.

Question 8

Assertion (A): CSV (Comma Separated Values) is a file format for data storage which looks like a text file.

Reasoning (R): In CSV file, the information is organized with one record on each line and each field is separate by comma.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

Both A and R are true and R is the correct explanation of A.

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 9

Assertion (A): Text file stores information in the ASCII or Unicode format/characters.

Reasoning (R): In a text file, there is no delimiter for a line.

  1. Both A and R are true and R is the correct explanation of A.
  2. Both A and R are true but R is not the correct explanation of A.
  3. A is true but R is false.
  4. A is false but R is true.

Answer

A is true but R is false.

Explanation
In a text file, information is stored in the form of ASCII or Unicode characters. Each line in a text file is terminated by a special character known as End of Line (EOL), and by default, this EOL character is the newline character (\n), which serves as the delimiter for lines in text files.

Solutions to Unsolved Questions

Question 1

What is the difference between "w" and "a" modes?

Answer

The differences between "w" and "a" modes are:

"w" mode"a" mode
The "w" mode in file opening is used for writing data to a file.The "a" mode in file opening is used for appending data to a file.
If the file exists, Python will truncate existing data and over-write in the file.If the file exists, the data in the file is retained and new data being written will be appended to the end of the file.

Question 2

What is the significance of file-object?

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

How are open() functions different from close() functions other than their functionality of opening and closing files?

Answer

open() functionsclose() functions
It creates a file object, which allows to perform various operations on the file, such as reading from it, writing to it, or appending data to it.When we're done working with a file, we should always close it using the close() function to free up system resources and prevent data loss.
The syntax is : file_objectname = open("filename", "mode")The syntax is : file.close()

Question 4

Write statements to open a binary file 'C:\Myfiles\text1.dat' in read and write mode by specifying the file path in two different formats.

Answer

The two different formats of specifying file path for opening the file C:\Myfiles\text1.dat in read and write mode are:

  1. file1 = open("C:\\Myfiles\\text1.dat", "rb+")

  2. file2 = open(r"C:\Myfiles\text1.dat", "rb+")

Question 5

In which of the following file modes will the existing data of the file 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+

Explanation
  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 6

What would be the data type of variable data in the following statements?

  1. data = f.read()
  2. data = f.read(10)
  3. data = f.readline()
  4. data = f.readlines()

Answer

  1. data = f.read() — Variable data will be string data type.
  2. data = f.read(10) — Variable data will be string data type.
  3. data = f.readline() — Variable data will be string data type.
  4. data = f.readlines() — Variable data will be list data type.

Question 7

When a file is opened for output in write mode, what happens when

(a) the mentioned file does not exist?
(b) the mentioned file exists?

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:

(a) 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.

(b) 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

What role is played by file modes in file operations? Describe the various file mode constants and their meanings.

Answer

File modes play a crucial role in file operations in Python as they determine how the file will be opened and what operations can be performed on it. Each file mode specifies whether the file should be opened for reading, writing, appending, or a combination of these operations. Additionally, file modes can distinguish between text mode and binary mode, which affects how the file data is handled.

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

Write a code snippet that will create an object called fileout for writing; associate it with the filename 'STRS'. The code should keep on writing strings to it as long as the user wants.

Answer

fileout = open('STRS.txt', 'w')
ans = 'y'
while ans == 'y':
    string = input("Enter a string: ")
    fileout.write(string + "\n")  
    ans = input("Want to enter more strings?(y/n)...")   
fileout.close()
Output
Enter a string: Hello
Want to enter more strings?(y/n)...y
Enter a string: World!
Want to enter more strings?(y/n)...n

The file "STRS.txt" includes:

Hello
World!

Question 10

Explain how many file objects would you need to create to manage the following situations:

(a) To process three files sequentially.

(b) To merge two sorted files into a third file.

Answer

(a) To process three files sequentially — In this scenario, where we need to process three files sequentially, we would need a single file object, as we can reuse a single file object by opening then processing and closing it for each file sequentially.

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 file2 in read mode and process it. Similarly, for file3 also we reuse the same file object f.

(b) 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 11

Write the advantages of saving data in:

(a) Binary form

(b) Text form

Answer

(a) The advantages of saving data in binary form are as follows:

  1. Efficiency — Binary files store data in a compact binary format, which can lead to smaller file sizes compared to text-based formats. Binary form is efficient for storing raw binary data.
  2. Speed — Reading and writing binary data can be faster than text-based formats because there is no need for encoding or decoding operations.
  3. Data Integrity — Binary files preserve the exact binary representation of data without any loss of information.

(b) The advantages of saving data in text form are as follows:

  1. Human Readability — Text-based formats, such as plain text files, are human-readable, making them easy to inspect and edit using a text editor.
  2. Interoperability — Text files can be easily shared and processed across different platforms and programming languages.
  3. Compatibility — Text-based formats are widely supported by various software applications and systems, making them a versatile choice for data interchange and communication.

Question 12

Why is it required to close a file after performing the reading and writing operations on a file?

Answer

It is a good practice to close a file once we are done with the read and write operations. When we close a file, the system frees the memory allocated to it. Python ensures that any unwritten or unsaved data is flushed (written) to the file before it is closed. Therefore, it is always advised to close the file once our work is done.

Question 13

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 14

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

Let the file "input.txt" include the following sample text:

In   the beginning  there  was    chaos.
Out of  the chaos  came order.
The universe  began to take shape.
Stars  formed  and galaxies were  born.
Life   emerged  in the  vast  expanse.
with open("input.txt", 'r') as f:
    with open("output.txt", 'w') as fout:
        for line in f:
            modified_line = ' '.join(line.split())
            fout.write(modified_line + '\n')

The file "output.txt" includes following text:

In the beginning there was chaos.
Out of the chaos came order.
The universe began to take shape.
Stars formed and galaxies were born.
Life emerged in the vast expanse.

Question 15

A file 'sports.dat' contains information in the following format: EventName, Participant

Write a function that would read contents from file 'sports.dat' and create a file named 'Athletic.dat' copying only those records from 'sports.dat' where the event name is "Athletics".

Answer

Let the file "sports.dat" include the following sample records:

Athletics - Rahul
Swimming - Tanvi
Athletics - Akash
Cycling - Kabir
Athletics - Riya
def filter_records(input_file, output_file):
    with open(input_file, 'r') as f_in:
        with open(output_file, 'w') as f_out:
            for line in f_in:
                event, participant = line.strip().split(' - ')
                if event == 'Athletics':
                    f_out.write(line)

filter_records('sports.dat', 'Athletic.dat')

The file "Atheletic.dat" includes following records:

Athletics - Rahul
Athletics - Akash
Athletics - Riya

Question 16

Write a program to count the words "to" and "the" present in a text file "Poem.txt".

Answer

Let the file "Poem.txt" include the following sample text:

To be or not to be, that is the question.
The quick brown fox jumps over the lazy dog.
To infinity and beyond!
The sun sets in the west.
To be successful, one must work hard.
to_count = 0
the_count = 0

with open("Poem.txt", 'r') as file:
    for line in file:
        words = line.split()
        for word in words:
            if word.lower() == 'to':
                to_count += 1
            elif word.lower() == 'the':
                the_count += 1

print("count of 'to': ", to_count)
print("count of 'the': ", the_count)
Output
count of 'to': 4
count of 'the': 5

Question 17

Write a program to count the number of uppercase alphabets present in a text file "Poem.txt".

Answer

Let the file "Poem.txt" include the following sample text:

PYTHON is a Popular Programming Language.
with open("Poem.txt", 'r') as file:
    text = file.read()
    count = 0
    for char in text:
        if char.isupper():
            count += 1

print(count)
Output
9

Question 18

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())
    
source_file = input("Enter the name of the source file: ")
destination_file = input("Enter the name of the destination file: ")

copy_file(source_file, destination_file)

Question 19

Write a program that appends the contents of one file to another. Have the program take the file names 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())
    
source_file = input("Enter the name of the source file: ")
destination_file = input("Enter the name of the destination file: ")

append_file(source_file, destination_file)

Question 20

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

The file "LOWER.txt" includes:

e
c

The file "UPPER.txt" includes:

A
D

The file "OTHERS.txt" includes:

7
@

Question 21

Write a program to search the names and addresses of persons having age more than 30 in the data list of persons stored in a text file.

Answer

Let the file "Persons.txt" include the following sample text:

Samyukta, Mumbai, 35
Anubhav, Chennai, 28
Aniket, Hyderabad, 42
Sarth, Bangalore, 31
f = open('Persons.txt', 'r')
lines = f.readlines()
for line in lines:
    data = line.strip().split(',')
    if len(data) >= 3 and int(data[2]) > 30:
        print('Name:', data[0], 'Address:', data[1])
f.close()        
Output
Name: Samyukta Address:  Mumbai
Name: Aniket Address:  Hyderabad
Name: Sarth Address:  Bangalore

Question 22

Write a function in Python to count and display the number of lines starting with alphabet 'A' present in a text file "LINES.TXT", e.g., the file "LINES.TXT" contains the following lines:

A boy is playing there. 
There is a playground.
An aeroplane is in the sky.
A cricket match is being played.

The function should display the output as 3.

Answer

The file "LINES.TXT" contains the following lines:

A boy is playing there.
There is a playground.
An aeroplane is in the sky.
A cricket match is being played.
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 23

Write the file mode that will be used for opening the following files. Also, write the Python statements to open the following files:

  1. a text file "example.txt" in both read and write mode.
  2. a binary file "bfile.dat" in write mode
  3. a text file "try.txt" in append and read mode
  4. a binary file "btry.dat" in read only mode

Answer

  1. File Mode: 'r+'
fh = open("example.txt", "r+")
  1. File Mode: 'wb'
fh = open("bfile.dat", "wb")
  1. File Mode: 'a+'
fh = open("try.txt", "a+")
  1. File Mode: 'rb'
fh = open("btry.dat", "rb")

Question 24

Why is it advised to close a file after we are done with the read and write operations? What will happen if we do not close it? Will some error message be flashed?

Answer

It is a good practice to close a file once we are done with the read and write operations. When we close a file, the system frees the memory allocated to it. Python ensures that any unwritten or unsaved data is flushed (written) to the file before it is closed. Therefore, it is always advised to close the file once our work is done. If we do not close file explicitly it will close automatically later when it's no longer in use or when the program terminates, without displaying any error message.

Question 25

What is the difference between the following sets of statements (a) and (b):

(a)

P = open("practice.txt", "r")  
P.read(10)

(b)

with open("practice.txt", "r") as P:  
    x = P.read()

Answer

The code given in (a) will open file "practice.txt" in read mode and will read 10 bytes from it. Also, it will not close the file explicitly. On the other hand, the code given in (b) will open file "practice.txt" in read mode and will read the entire content of the file. Furthermore, it will automatically close the file after executing the code due to the with clause.

Question 26

Write a program to accept string/sentences from the user till the user enters "END". Save the data in a text file and then display only those sentences which begin with an uppercase alphabet.

Answer

f = open("new.txt", "w")
while True:
    st = input("Enter next line:")
    if st == "END":
        break
    f.write(st + '\n')
f.close()

f = open("new.txt", "r")
while True:
    st = f.readline()
    if not st:
        break
    if st[0].isupper():
        print(st)
f.close()
Output
Enter next line:Hello world
Enter next line:welcome to     
Enter next line:Python programming
Enter next line:END
Hello world

Python programming

Question 27

Write a function to insert a sentence in a text file, assuming that text file is very big and can't fit in computer's memory.

Answer

Let the file "insert.txt" include the following sample text:

Bees hum
leaves rustle
Waves crash
nature's voice whispers
def insert_sentence(file_path, sentence):
    file = open(file_path, 'a')
    file.write(sentence + '\n')
    file.close()
insert_sentence("insert.txt", "life's essence glimmers")

The "insert.txt" file includes following text:

Bees hum
leaves rustle
Waves crash
nature's voice whispers
life's essence glimmers

Question 28

Write a program to read a file 'Story.txt' and create another file, storing an index of 'Story.txt', telling which line of the file each word appears in. If word appears more than once, then index should-show all the line numbers containing the word.

Answer

Let the file "Story.txt" include the following sample text:

The cat sleeps
The dog barks
The cat jumps
The sun shines
word_index = {}
file = open('Story.txt', 'r')
line_number = 1
lines = file.readlines()
for line in lines:
    words = line.strip().split()
    for word in words:
        if word in word_index:
            word_index[word].append(str(line_number))
        else:
            word_index[word] = [str(line_number)]
    line_number += 1
file.close()

index_file = open('index.txt', 'w')
for word, line_numbers in word_index.items():
    line_numbers_str = ", ".join(line_numbers)
    index_file.write(word + ":" + line_numbers_str + "\n")
index_file.close()

The "index.txt" file includes following text:

The:1, 2, 3, 4
cat:1, 3
sleeps:1
dog:2
barks:2
jumps:3
sun:4
shines:4

Question 29

Write a program to accept a filename from the user and display all the lines from the file which contain Python comment character '#'.

Answer

Let the file "notes.txt" include the following sample text:

Welcome to the Garden of Dreams 
#where the ordinary becomes extraordinary
#the impossible becomes possible.
file_name = input("Enter the filename: ")
file = open(file_name, 'r')
lines = file.readlines()
for line in lines:
    if '#' in line:
        print(line)
file.close()
Output
Enter the filename: notes.txt
#where the ordinary becomes extraordinary
#the impossible becomes possible.

Question 30

Reading a file line by line from the beginning is a common task. What if you want to read a file backward ? This happens when you need to read log files. Write a program to read and display content of file from end to beginning.

Answer

Let the file "logs.txt" include the following sample text:

[2022-04-15 10:00:00] INFO: Application started
[2022-04-15 10:05:00] ERROR: Database connection failed
[2022-04-15 10:10:00] WARNING: Disk space low
[2022-04-15 10:15:00] INFO: User logged in: username=john, ip_address=192.168.1.100
file_name = input("Enter the filename: ")
f = open(file_name, 'r')
lines = f.readlines()
for line in lines[::-1]:
    print(line.rstrip())  
f.close()
Output
Enter the filename: logs.txt 
[2022-04-15 10:15:00] INFO: User logged in: username=john, ip_address=192.168.1.100
[2022-04-15 10:10:00] WARNING: Disk space low
[2022-04-15 10:05:00] ERROR: Database connection failed
[2022-04-15 10:00:00] INFO: Application started

Question 31

Write a Python program to display the size of a file after removing EOL characters, leading and trailing white spaces and blank lines.

Answer

Let the file "sample.txt" include the following sample text:

  The sky is blue\n 
  
  Clouds float gently in the sky.   
  
  Birds sing sweet melodies.   
file = open('sample.txt', 'r')
lines = file.readlines()
original_size = 0
for line in lines:
    original_size += len(line)
print("Original file size:", original_size)
file.close()

file = open('sample.txt', 'r')
cleaned_size = 0
for line in file:
    cleaned_line = line.strip()
    if cleaned_line:
        cleaned_size += len(cleaned_line)
file.close()
print("Cleaned file size:", cleaned_size)
Output
Original file size: 126
Cleaned file size: 74

Question 32

Write a function Remove_Lowercase() that accepts two file names, and copies all lines that do not start with lowercase letter from the first file into the second file.

Answer

Let the file "file1.txt" include the following sample text:

Dew on petals, morning's gift.
silent moon, silver glow.
Winds whisper, secrets shared.
rain's embrace, earth's renewal.
def Remove_Lowercase(input_file, output_file):
    input_file = open(input_file, 'r')
    output_file = open(output_file, 'w')
    for line in input_file:
        if line.strip() and line[0].isupper():
            output_file.write(line)
    input_file.close()
    output_file.close()

input_file = 'file1.txt'
output_file = 'file2.txt'
Remove_Lowercase(input_file, output_file)

The file "file2.txt" includes following text:

Dew on petals, morning's gift.
Winds whisper, secrets shared.

Question 33

Write a program to display all the records in a file along with line/record number.

Answer

Let the file "f1.txt" include the following sample text:

Soft whispers of the wind.
A melody in the trees.
Sun-kissed petals dance.
A garden's quiet song.
file_name = 'f1.txt'
line_number = 1
f = open(file_name, 'r')
for line in f:
    print("Line", line_number, ":", line.strip())
    line_number += 1
f.close()
Output
Line 1 : Soft whispers of the wind.
Line 2 : A melody in the trees.
Line 3 : Sun-kissed petals dance.
Line 4 : A garden's quiet song.

Question 34

Write a method in Python to write multiple line of text contents into a text file "mylife.txt".

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")

Question 35

Write a method in Python to read the content from a text file "DIARY.TXT" line by line and display the same on the 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 36

Write appropriate statements to do the following:

(a) To open a file named "RESULT.DAT" for output.

(b) To go to the end of the file at any time.

Answer

(a) To open a file named "RESULT.DAT" for output:
file = open("RESULT.DAT")

(b) To go to the end of the file at any time:
file.seek(0, 2)

Question 37

Write a program to add two more employees' details (empno, ename, salary, designation) to the file "emp.txt" already stored in disk.

Answer

Let the file "emp.txt" include the following sample text:

1001, Ankit Singh, 50000, Manager
1002, Neha Patel, 45000, Developer
file = open("emp.txt", "a")
file.write("1003, Manoj Tiwari, 48000, Analyst\n")
file.write("1004, Aarti Gupta, 52000, Engineer\n")

The file "emp.txt" include the following text:

1001, Ankit Singh, 50000, Manager
1002, Neha Patel, 45000, Developer
1003, Manoj Tiwari, 48000, Analyst
1004, Aarti Gupta, 52000, Engineer

Question 38

How are the following codes different from one another?

1.

fp = open("file.txt", 'r')  
fp.read()

2.

fp = open("file.txt", 'r')

Answer

The first code opens 'file.txt' in read mode, initializes a file object (fp) for further file operations, and reads its entire content using fp.read(). The second code also opens 'file.txt' in read mode, initializes a file object (fp) for further file operations, but it doesn't perform any read operation.

Question 39

What is the output of the following code fragment? Explain.

fout = open("output.txt", 'w') 
fout.write("Hello, world! \n") 
fout.write("How are you?") 
fout.close()
f = open("output.txt")
print(f.read())

Answer

Output
Hello, world! 
How are you?

The code first opens a file named 'output.txt' in write mode ('w'), writes the strings 'Hello, world!' and 'How are you?' to the file with a newline character in between, creating a new line between the two strings in the file. It then closes the file and reopens it again in read mode (default mode). Finally, it reads the entire content of the file and prints it.

Question 40

Write the output of the following code with justification if the contents of the file "ABC.txt" are:

"Welcome to Python Programming!"

f1 = open("ABC.txt", "r")
size = len(f1.read())
print(size)
data = f1.read(5)
print(data)

Answer

Output
30

The code opens the file 'ABC.txt' in read mode ('r') and creates a file object named f1. The next line, size = len(f1.read()), reads the entire contents of the file 'ABC.txt', returning a string containing the file's contents. Then, len() calculates the length of this string and assigns it to the variable size. After the f1.read() operation, the file pointer is positioned at the end of the file. The code then prints the size. The subsequent line, data = f1.read(5), attempts to read the first 5 characters from the file 'ABC.txt' using f1.read(5). However, since the file pointer is already at the end of the file, there are no characters left to read. Therefore, this read(5) operation will return an empty string. Finally, the code prints the value of data, which is an empty string.

Question 41

Give the output of the following snippet:

import pickle
list1, list2 = [2, 3, 4, 5, 6, 7, 8, 9, 10], []
for i in list1:
    if (i % 2 == 0 and i % 4 == 0):
        list2.append(i)
f = open("bin.dat", "wb")
pickle.dump(list2, f)
f.close()
f = open("bin.dat", "rb")
data = pickle.load(f)
f.close()
for i in data: 
    print(i)

Answer

Output
4
8
Explanation

The code imports pickle module in Python. Initially, it creates two lists: list1 with numbers from 2 to 10 and list2 as an empty list. It then iterates through list1 and appends numbers divisible by both 2 and 4 to list2. After that, it opens a binary file named "bin.dat" in write-binary mode ("wb") and uses pickle.dump() to serialize list2 and write it to the file. The file is then closed. Later, the code opens the same file in read-binary mode ("rb") and uses pickle.load() to deserialize the data from the file into the variable data. Finally, it iterates through data and prints each element, which in this case are the numbers from list2 that satisfy the conditions (divisible by both 2 and 4).

Question 42

Anant has been asked to display all the students who have scored less than 40 for Remedial Classes. Write a user-defined function to display all those students who have scored less than 40 from the binary file "Student.dat".

Answer

Let the file "Student.dat" include the following sample data:

Radhika 80
Shaurya 35
Sonia 38
Anirudh 45
import pickle

def display_students(file_name):
        file = open(file_name, 'rb')
        students = pickle.load(file) 
        for student in students:
            name = student[0]
            score = student[1]
            if score < 40:
                print(name)
        file.close()
display_students('student.dat')
Output
Shaurya
Sonia

Question 43

Following is the structure of each record in a data file named "PRODUCT.DAT".

{"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 integer.

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.

Answer

Let the file "PRODUCT.dat" include the following sample data:

{'prod_code': 'AB', 'prod_desc': 'Books', 'stock': 50}
{'prod_code': 'AC', 'prod_desc': 'Pens', 'stock': 75}
{'prod_code': 'AD', 'prod_desc': 'Pencils', 'stock': 30}
import pickle

def update_stock(file_name, product_code, new_stock):
    products = [] 
    f = open(file_name, 'rb')
    while True:
        try:
            product = pickle.load(f)
            products.append(product)
        except EOFError:
            break
    f.close()               
    updated = False
    for product in products:
        if product['prod_code'] == product_code:
            product['stock'] = new_stock
            updated = True
            break  
    f = open(file_name, 'wb')
    for product in products:
       pickle.dump(product, f)
    f.close()
P_code = input("Enter the product code: ")
New = int(input("Enter the new stock value: "))
update_stock('PRODUCT.DAT', P_code, New)
Output
Enter the product code: AB
Enter the new stock value: 100

The file "PRODUCT.dat" include the following updated data:

{'prod_code': 'AB', 'prod_desc': 'Books', 'stock': 100}
{'prod_code': 'AC', 'prod_desc': 'Pens', 'stock': 75}
{'prod_code': 'AD', 'prod_desc': 'Pencils', 'stock': 30}

Question 44

Given a binary file "STUDENT.DAT", containing records of the following type:

[S_Admno, S_Name, Percentage]

Where these three values are:

S_Admno — Admission Number of student (string)
S_Name — Name of student (string)
Percentage — Marks percentage of student (float)

Write a function in Python that would read contents of the file "STUDENT.DAT" and display the details of those students whose percentage is above 75.

Answer

Let the file "STUDENT.dat" include the following sample data:

[['101', 'Aishwarya', 97.0], 
['102', 'Sakshi', 85.0], 
['103', 'Prateek', 70.0]]
import pickle

def display_students(filename):
        file = open(filename, 'rb')
        student_records = pickle.load(file)
        above_75 = []
        for student in student_records:
            if student[2] > 75.0:
                above_75.append(student)
        if above_75:
            print("Students with percentage above 75:")
            for student in above_75:
                print("Admission Number:", student[0], "Name:", student[1], "Percentage:", student[2])
        file.close()
display_students("STUDENT.DAT")
Output
Students with percentage above 75:
Admission Number: 101 Name: Aishwarya Percentage: 97.0
Admission Number: 102 Name: Sakshi Percentage: 85.0

Question 45

Write a statement to open a binary file C:\Myfiles\Text1.dat in read and write mode by specifying for file path in two different formats.

Answer

The two different formats of specifying file path for opening the file C:\Myfiles\Text1.txt in read and write mode are:

  1. file1 = open("C:\\Myfiles\\Text1.txt", "rb+")

  2. file2 = open(r"C:\Myfiles\Text1.txt", "rb+")

Question 46

Write a statement in Python to perform the following operations:

(a) To open a text file "BOOK.TXT" in read and append mode

(b) To open a text file "BOOK.TXT" in write mode

(c) To open a text file "BOOK.TXT" in append mode

Answer

(a) To open a text file "BOOK.TXT" in read and append mode :
file_read_append = open("BOOK.TXT", "a+")

(b) To open a text file "BOOK.TXT" in write mode :
file2 = open("BOOK.TXT", "w")

(c) To open a text file "BOOK.TXT" in append mode :
file_append = open("BOOK.TXT", "a")

Question 47

What is the following code doing?

import csv
File = open("contacts.csv", "a")
Name = input("Please enter name: ")
Phno = input("Please enter phone number: ") 
data = [Name, Phno]
csvwriter = csv.writer(File)
csvwriter.writerow(data)
File.close()

Answer

The code imports the CSV module, opens 'contacts.csv' in append mode, prompts the user for input of a name and phone number, writes data to the CSV file, and then closes the file.

Question 48

Write code to open the file in the previous question and print it in the following form:

Name : <name>    Phone: <phone number>

Answer

Let the file "contacts.csv" include the following sample data:

Aniketh,9876546707
Sanjeeth,8976548689
Amrutha,6786778908
import csv
with open("con.csv", "r") as file:
    csvreader = csv.reader(file)
    for row in csvreader:
        if row:
            name = row[0]
            phone = row[1]
            print("Name:", name,"\t\t" "Phone:", phone)
Output
Name: Aniketh         Phone: 7868478767
Name: Sanjeeth        Phone: 6766474789
Name: Amrutha         Phone: 8749374678

Question 49

Consider the file "contacts.csv" created in the question above 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
  1. name = input("Enter name :") — This line prompts the user to enter a name through the console, and the entered name is stored in the variable name.
  2. file = open("contacts.csv", "r") — This line opens the file contacts.csv in read mode and assigns the file object to the variable file.
  3. for line in file: — This line initiates a for loop that iterates over each line in the file handle (file represents the opened file object), which enables interaction with the file's content. During each iteration, the current line is stored in the variable line.
  4. if name in line: — Within the loop, it checks if the inputted name exists in the current line using the in operator.
  5. print(line) — If the name is found in the current line, this line prints the entire line to the console.

Question 50

Write a program to enter the following records in a binary file:

Item No — integer
Item_Name — string
Qty — integer
Price — float

Number of records to be entered should be accepted from the user. Read the file to display the records in the following format:

Item No:
Item Name:
Quantity:
Price per item:
Amount: (to be calculated as Price * Qty)

Answer

import pickle

with open("item.dat", 'wb') as itemfile:
    n = int(input("How many records to be entered? "))
    for i in range(n):
        ino = int(input("Enter item no: "))
        iname = input("Enter item name: ")
        qty = int(input("Enter quantity: "))
        price = float(input("Enter price: "))
        item = {"Item no": ino, "Item Name": iname, "Qty": qty, "Price": price}
        pickle.dump(item, itemfile)
    print("Successfully written item data")


with open("item.dat", "rb") as file:
    try:
        while True:
            item = pickle.load(file)
            print("\nItem No:", item["Item no"])
            print("Item Name:", item["Item Name"])
            print("Quantity:", item["Qty"])
            print("Price per item:", item["Price"])
            print("Amount:", item["Qty"] * item["Price"])
    except EOFError:
        pass  
Output
How many records to be entered? 5
Enter item no: 11
Enter item name: Mobile
Enter quantity: 4
Enter price: 20000
Enter item no: 12
Enter item name: Laptop
Enter quantity: 2
Enter price: 35000
Enter item no: 13
Enter item name: Computer
Enter quantity: 1
Enter price: 50000
Enter item no: 14
Enter item name: Television
Enter quantity: 4
Enter price: 25000 

Item No: 11
Item Name: Mobile
Quantity: 4
Price per item: 20000.0
Amount: 80000.0

Item No: 12
Item Name: Laptop
Quantity: 2
Price per item: 35000.0
Amount: 70000.0

Item No: 13
Item Name: Computer
Quantity: 1
Price per item: 50000.0
Amount: 50000.0

Item No: 14
Item Name: Television
Quantity: 4
Price per item: 25000.0
Amount: 100000.0

Question 51

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.

Answer

import csv

with open("Groceries.csv", mode = 'w', newline = '') as file:
    writer = csv.writer(file)
    
    while True:
        item_code = int(input("Enter Item Code: "))        
        name = input("Enter Name of the Item: ")
        price = float(input("Enter Price: "))
        quantity = int(input("Enter Quantity: "))
        
        writer.writerow([item_code, name, price, quantity])
        choice = input("Wish to enter more records (Y/N)?: ")
        if choice.upper() == 'N':
            break

The file "Groceries.csv" includes following records:

101,Soaps,45.5,5
102,Atta,34.0,2
103,Maggie,70.0,1
PrevNext