Loading...
Please wait while we prepare your content
Please wait while we prepare your content
Solutions for Computer Science, Class 12, CBSE
(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.
(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.
(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.
(b)
Both Assertion and Reason are true but Reason is not the correct explanation of Assertion.
Explanation
A binary file works with byte-streams and 'Pickling' is the process in binary file, where a Python object hierarchy is converted into a byte-stream. Binary files are commonly used as the destination for pickled data. This is because binary files can efficiently store raw binary data, including the byte-streams produced by pickling.
(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.
(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.
(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.
'rb', ab, a + b, r+
Reason —
A text file stores information in ASCII or Unicode characters, where each line of text is terminated, (delimited) with a special character known as EOL (End of line) character. In text files some internal manipulations take place when this EOL character is read and written.
A binary file stores the information in form of a stream of bytes. A binary file is just a file that contains information in the same format in which the information is held in memory, i.e., the file content that is returned to us is raw (with no translation or no specific encoding).
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).
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.
Text files, Binary files
Reason —
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.
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).
file = open("c:\\ss.txt", "a")
file = open(r"c:\ss.txt", "a")
Reason —
file = open("c:\\ss.txt", "a")
— The syntax to open a file c:\ss.txt
is f = open("c:\\temp\\data.txt", "a")
. Hence according to this syntax file = open("c:\\ss.txt", "a")
is correct format.file = open(r"c:\ss.txt", "a")
— The syntax to open a file c:\ss.txt
with single slash is f = open(r"c:\temp\data.txt","a")
.The prefix r in front of a string makes it raw string that means there is no special meaning attached to any character. Hence according to this syntax file = open(r"c:\ss.txt", "a")
is correct format.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.
infi.readlines()
Reason — The syntax to read all lines in a file is <filehandle>.readlines()
. Hence according to this syntax infi.readlines() is correct format.
Which of the following statement is not correct ?
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.
Which of the following option is the correct Python statement to read and display the first 10 characters of a text file "Notes.txt" ?
F = open('Notes.txt') ; print(F.read(10))
Reason — The syntax to read and display the first 10 characters of a text file is f = open(file-name) ; print(f.read(10))
. Hence according to this syntax, F = open('Notes.txt') ; print(F.read(10))
format is correct.
F = open('Notes.txt', 'A')
Reason — F = open('Notes.txt', 'A')
, in this statement mode should be written in small letter 'a'. So the correct statement would be F = open('Notes.txt', 'a')
.
fin = open("c:\\pat.txt", "r")
Reason — The syntax to open a file in read-mode only is f = open("c:\\temp\\data.txt", "r")
. Hence according to this syntax fin = open("c:\\pat.txt", "r")
format is correct.
Which of the following statements are true regarding the opening modes of a file ?
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 —
fout = open("c:\\pat.txt", "wb")
Reason — The syntax to open a file for writing in binary format is f = open("c:\\temp\\data.txt", "wb")
. Hence according to this syntax fout = open("c:\\pat.txt", "wb")
format is correct.
fout = open("c:\\pat.txt", "wb+")
Reason — The syntax to open a file for writing as well as reading in binary format is f = open("c:\\temp\\data.txt", "wb+")
. Hence according to this syntax fout = open("c:\\pat.txt", "wb+")
format is correct.
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>)
.
Which of the following option is the correct usage for the tell() of a file object ?
It returns the byte position of the file pointer as an integer.
Reason — The tell() function returns the current byte position of file pointer in the file as an integer.
Which of the following statement is incorrect in the context of pickled binary files ?
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.
It places the file pointer at a desired offset within the file.
Reason — The seek() function changes the position of the file-pointer by placing the file-pointer at the specified position in the open file.
file_object.seek(offset[, reference_point])
Reason — The syntax of seek() function is <file-object>.seek(offset[, mode])
.
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.
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.
True
Reason — If no path is given with a file name in the open() function in Python, then the file is assumed to be located in the current working directory. If the file is not found in the current working directory, Python will raise a 'FileNotFoundError' exception.
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.
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.
False
Reason — The load() function of the pickle module performs unpickling i.e., a byte stream is converted into an object hierarchy. It is used to read an object on to a binary file opened in a read mode.
False
Reason — The dump() function of the pickle module performs pickling i.e, an object hierarchy is converted into a byte stream. It is used to write an object on to a binary file opened in a write mode.
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. |
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.
open() function | close() function |
---|---|
The open() function is used to open a file. | The close() function is used to close a file object. |
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() |
The two different formats of specifying file path for opening the file C:\Myfiles\Text1.txt
in read and write mode are:
file1 = open("C:\\Myfiles\\Text1.txt", "rb+")
file2 = open(r"C:\Myfiles\Text1.txt", "rb+")
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.
reader()
Reason — In the CSV module in Python, the reader() function is used to read the contents of a CSV file into an object. This function returns a reader object which can be used to iterate over the rows of the CSV file, where each row is represented as a list of strings. This allows to process the data contained within the CSV file.
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.
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:
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.
(i) The advantages of saving data in binary form are as follows:
(ii) The advantages of saving data in text form are as follows:
(iii) The advantages of saving data in CSV files are as follows:
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.
(a) To open a text file "BOOK.TXT" in read mode : file1 = open("BOOK.TXT", "r")
(b) To open a text file "BOOK.TXT" in write mode : file2 = open("BOOK.TXT", "w")
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.
(i) 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 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()
A CSV (Comma-Separated Values) file is a specific type of text file. The similarities and differences of CSV files with text files are as follows :
The similarities :
The differences :
Yes, a CSV (Comma-Separated Values) file is different from a binary file. A CSV (Comma-Separated Values) file differs from a binary file in several aspects. CSV files are text-based and structured to store tabular data, with records separated by line breaks and fields by delimiters like commas. They are human-readable and editable using text editors, facilitating data interchange between applications and platforms. In contrast, binary files store data in a non-text, machine-readable format, represented by sequences of bytes. There is no delimiter for a line and no character translations occur. They accommodate diverse data types like images, audio, but are not human-readable and require specialized software for interpretation.
CSV (Comma-Separated Values) files are popular for data storage due to the following reasons:
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:
We may need to suppress the end-of-line (EOL) translation in CSV file handling in Python in specific situations where precise control over line endings is necessary. Different operating systems utilize different conventions for representing line endings in text files. For instance, Windows uses \r\n (carriage return + line feed), Unix-based systems (Linux, macOS) use \n (line feed), and classic Mac OS used \r (carriage return). When reading or writing CSV files intended for compatibility across multiple platforms, suppressing EOL translation ensures that line endings are preserved exactly as they are, without automatic conversion to the platform-specific convention. To suppress EOL translation in CSV file handling in Python, we can use the newline='' parameter when opening the file with the open() function. This parameter instructs Python to suppress EOL translation and preserve the original line endings in the file.
Renaming a text file's extension to ".csv" does not automatically convert it into a CSV (Comma-Separated Values) file. To create a CSV file, we need to ensure that the file's content adheres to :
"w" mode | "r" mode |
---|---|
It is also called as write mode. | It is also called as read mode. |
The "w" mode is used to open a file for writing. | The "r" mode is used to open a file for reading. |
It creates a new file if the file does not exist. | If the file does not exist, it raises a FileNotFoundError. |
If the file exists, Python will truncate existing data and over-write in the file. | If the file exists, Python will open it for reading and allow to access its contents. |
Example: with open("example.txt", "w") as file: file.write("Hello, world!\n") | Example: with open("example.txt", "r") as file: data = file.read() print(data) |
(i) f = open('diary.txt', 'r')
— This line opens the file diary.txt
in read mode ('r'). If the file does not exist, Python will raise an error. If the file exists, the data will not be erased.
(ii) f = open('diary.txt', 'w')
— This line opens the file diary.txt
in write mode ('w'). If the file does not exist, Python creates new file with the specified name. If the file exists, Python will truncate existing data and over-write in the file.
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.
If the file 'poemBTH.txt' contains the following poem (by Paramhans Yoganand) :
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!
Then what outputs will be produced by both the code fragments given in question1.
(a)
my_file = open('poemBTH.txt', 'r')
my_file.read()
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!
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)
God made the Earth;
Man made confining countries
And their fancy-frozen boundaries.
But with unfound
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.
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()
The code will result in an error because at line 3 there is a syntax error. The correct syntax is s2 = obj1.readline()
.
The corrected code will be:
obj1 = open("poemBTH.txt", "r")
s1 = obj1.readline()
s2 = obj1.readline()
s3 = obj1.read(15)
print(s3)
print(obj1.readline())
obj1.close()
And their fancy
-frozen boundaries.
obj1 = open("poemBTH.txt", "r")
— This line opens the file named poemBTH.txt
in read mode ("r") and assigns the file object to the variable obj1
.s1 = obj1.readline()
— This line reads the first line from the file obj1 and assigns it to the variable s1
.s2 = obj1.readline()
— This line reads the next line from the file obj1, starting from the position where the file pointer currently is, which is the beginning of the second line (from the previous readline() call). Then assigns it to the variable s2
.s3 = obj1.read(15)
— This line reads the next 15 characters from the file obj1, starting from the position where the file pointer currently is, which is the beginning of third line (from the previous readline() call) and assigns them to the variable s3
.print(s3)
— This line prints the contents of s3.print(obj1.readline())
— This line attempts to read the next line from the file obj1 and print it. However, since the file pointer is already ahead by 15 characters (from the previous read(15) call), this line will start reading from where the file pointer is currently positioned i.e., from "-" up to end of line.obj1.close()
— This line closes the file obj1.Let the file "contacts.txt" include following sample text:
Kumar 8574075846
Priya 5873472904
Neetu 7897656378
with open("contacts.txt", "r") as file:
for line in file:
name, phone = line.strip().split()
print("Name: " + name + " \t Phone: " + phone)
Name: Kumar Phone: 8574075846
Name: Priya Phone: 5873472904
Name: Neetu Phone: 7897656378
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.
As mentioned in the note, the output of above code fragments together in succession is as follows:
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
E. Output of Readlines function is
[]
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.
This code opens a CSV file named contacts.csv
in append mode, as indicated by the mode "a". This mode allows new data to be added to the end of the file without overwriting existing content. It then prompts the user to enter a name and a phone number through the console using the input()
function. After receiving input, it concatenates the name and phno separated by a comma, and appends a newline character '\n' to signify the end of the line. Finally, it writes this concatenated string to the CSV file using the write()
method of the file object. This operation effectively adds a new record to the CSV file with the provided name and phone number.
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.
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
.file = open("contacts.csv", "r")
— This line opens the file contacts.csv
in read mode and assigns the file object to the variable file
.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
.if name in line:
— Within the loop, it checks if the inputted name exists in the current line using the in
operator.print(line)
— If the name is found in the current line, this line prints the entire line to the console.The code is calculating the number of lines present in the file poemBTH.txt.
7
f = open("poemBTH.txt", "r")
— This line opens a file named poemBTH.txt
in read mode ("r") and assigns the file object to the variable f
.nl = 0
— This line initializes a variable nl
to 0.for line in f:
— By iterating over the file handle using a for loop as shown, we can read the contents of the file line by line.nl += 1
— Within the for
loop, this statement increments the value of nl
by 1 for each iteration, effectively counting the number of lines in the file.print(nl)
— After the for loop completes, this statement prints the value of nl
, which represents the total number of lines in the file.def diary_content(f):
myfile = open(f, "r")
str = " "
while str:
str = myfile.readline()
print(str, end = '')
myfile.close()
diary_content("diary.txt")
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")
Dunzo
import pickle
— Imports the pickle
module, which is used for serializing and deserializing Python objects.ID = {1: "Ziva", 2: "53050", 3: "IT", 4: "38", 5: "Dunzo"}
— Defines a dictionary named ID
with keys and values.fin = open("Emp.pkl", "wb")
— Opens a file named Emp.pkl
in binary write mode ("wb").pickle.dump(ID, fin)
— Serializes the ID
dictionary and writes it to the file handle fin
using the pickle.dump()
function.fin.close()
— Closes the file fin
after writing the pickled data.fout = open("Emp.pkl", 'rb')
— Opens the file Emp.pkl
again, this time in binary read mode ("rb"), to read the pickled data.ID = pickle.load(fout)
— Deserializes the data from the file fout
using the pickle.load()
function and assigns it to the variable ID
. This effectively restores the original dictionary from the pickled data.print(ID[5])
— Prints the value associated with key 5 in the restored ID
dictionary, which is "Dunzo".What will be the output of the following code ?
import pickle
List1 = ['Roza', {'a': 23, 'b': True}, (1, 2, 3), [['dogs', 'cats'], None]]
List2 = ['Rita', {'x': 45, 'y': False}, (9, 5, 3), [['insects', 'bees'], None]]
with open('data.pkl', 'wb') as f:
f.write(List1)
with open('data.pkl', 'wb') as f:
f.write(List2)
with open('data.pkl', 'rb') as f:
List1 = pickle.load(f)
print(List1)
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.
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)
This code will produce no output.
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.
import csv
f = open('attendees1.csv') #error
csv_f = csv.writer(f)
To use the csv.writer()
function, the file should be opened in write mode ('w'). The corrected code is :
import csv
f = open('attendees1.csv', 'w')
csv_f = csv.writer(f)
import csv
f = open('attendees1.csv') #error 1
csv_f = csv.reader() #error 2
for row in csv_f:
print(row)
csv.reader()
function, the file should be opened in read mode ('r').<name-of-reader-object> = csv.reader(<file-handle>)
.The corrected code is :
import csv
f = open('attendees1.csv', 'r')
csv_f = csv.reader(f)
for row in csv_f:
print(row)
import pickle
data = ['one', 2, [3, 4, 5]]
with open('data.dat', 'wb' : #error 1
pickle.dump(data) #error 2
open()
function call. The closing parenthesis is missing in the open()
function call. Also, file handle is not mentioned.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.The corrected code is :
import pickle
data = ['one', 2, [3, 4, 5]]
with open('data.dat', 'wb') as f:
pickle.dump(data, f)
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.
A file sports.dat contains information in following format:
Event - Participant
Write a function that would read contents from file sports.dat and creates a file named Atheletic.dat copying only those records from sports.dat where the event name is "Atheletics".
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
A file contains a list of telephone numbers in the following form:
Arvind 7258031
Sachin 7259197
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.
Let the file "telephone.txt" include the following sample records:
Arvind 7258031
Sachin 7259197
Karuna 8479939
with open("telephone.txt", "r") as file:
f = file.readlines()
for line in f:
name, number = line.split()
print(name, '\t\t' ,number)
Arvind 7258031
Sachin 7259197
Karuna 8479939
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)
count of 'to': 4
count of 'the': 5
Write a function AMCount() in Python, which should read each character of a text file STORY.TXT, should count and display the occurrence of alphabets A and M (including small cases a and m too).
Example :
If the file content is as follows :
Updated information
As simplified by official websites.
The EUCount() function should display the output as :
A or a : 4
M or m : 2
Let the file "STORY.TXT" include the following sample text:
Updated information
As simplified by official websites.
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
print("A or a:", count_a)
print("M or m:", count_m)
AMCount("STORY.TXT")
A or a: 4
M or m: 2
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)
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)
Let the file "MYNOTES.TXT" include the following sample text:
Kangaroo is a mammal native to Australia.
Lion is a large carnivorous.
Koala is an arboreal herbivorous.
Elephant is a large herbivorous mammal.
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")
Kangaroo is a mammal native to Australia.
Koala is an arboreal herbivorous.
Let "STORY.TXT" file contain the following text:
Once upon a time, there was a little boy named Jay
He had a dog named Leo
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")
a
was
a
boy
Jay
He
had
a
dog
Leo
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.
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()
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
@
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.
Alphabets & numbers are allowed in password.
the function should display the output as 3.
The file "LINES.TXT" contains the following lines:
A boy is playing there.
There is a playground.
An aeroplane is in the sky.
Alphabets & numbers are allowed in password.
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")
3
Let the sample file "myfile.txt" contain the following text:
Hello world! This is a test file.
It contains some characters until the first $ is encountered.
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)
78
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)...")
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!
import pickle
member1 = {'MemberNo.': '123456', 'Name': 'Pranav'}
member2 = {'MemberNo.': '456235', 'Name': 'Aman'}
def write_member():
file = open("member.dat", 'wb')
pickle.dump(member1, file)
pickle.dump(member2, file)
file.close()
write_member()
Consider the following definition of dictionary Staff, write a method in python to search and display content in a pickled file staff.dat, where Staffcode key of the dictionary is matching with 'S0105'.
Staff = {'Staffcode': ..............., 'Name' = ...............}
Let the file "staff.dat" include following data:
Staff1 = {'Staffcode': 'S0102', 'Name': 'Sanya'}
Staff2 = {'Staffcode': 'S0104', 'Name': 'Anand'}
Staff3 = {'Staffcode': 'S0105', 'Name': 'Aditya'}
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')
Staffcode: S0105
Name: Aditya
Considering the following definition of dictionary COMPANY, write a method in Python to search and display the content in a pickled file COMPANY.DAT, where CompID key of the dictionary is matching with the value '1005'.
Company = {'CompID' = ........., 'CName' = ........., 'Turnover' = .........}
Let the file "COMPANY.DAT" include following data:
Company1 = {'CompID': '1001', 'CName': 'ABC', 'Turnover': 500000}
Company2 = {'CompID': '1003', 'CName': 'DEF', 'Turnover': 600000}
Company3 = {'CompID': '1005', 'CName': 'LMN', 'Turnover': 900000}
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')
Company ID: 1005
Company Name: LMN
Turnover: 900000
Write a function to search and display details of all trains, whose destination is "Delhi" from a binary file "TRAIN.DAT". Assuming the binary file is containing the objects of the following dictionary type:
Train = {'Tno': ..............., 'From': ...............,'To': ...............}
Let the dictionary contained in file "TRAIN.DAT" be as shown below:
Train1 = {'Tno': '1234', 'From': 'Mumbai', 'To': 'Delhi'}
Train2 = {'Tno': '5678', 'From': 'Chennai', 'To': 'Delhi'}
Train3 = {'Tno': '9012', 'From': 'Kolkata', 'To': 'Mumbai'}
Train4 = {'Tno': '3456', 'From': 'Delhi', 'To': 'Bangalore'}
Train5 = {'Tno': '7890', 'From': 'Pune', 'To': 'Delhi'}
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()
Train no: 1234
From: Mumbai
To: Delhi
Train no: 5678
From: Chennai
To: Delhi
Train no: 7890
From: Pune
To: Delhi
Search Successful
A binary file "Book.dat" has structure [BookNo, Book_Name, Author, Price].
(i) Write a user defined function CreateFile() to input data for a record and add to Book.dat.
(ii) Write a function CountRec(Author) in Python which accepts the Author name as parameter and count and return number of books by the given Author are stored in the binary file "Book.dat"
Let the file "Book.dat" include following data:
Book1 = [1001, Midnight's Children, Salman Rushdie, 29.99]
Book2 = [1004, A Suitable Boy, Vikram Seth, 59.9]
Book3 = [1003, The White Tiger, Aravind Adiga, 49.5]
Book4 = [1002, The Satanic Verses, Salman Rushdie, 39.23]
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))
Enter Book Number: 1008
Enter Book Name: Three Thousand Stiches
Enter Author Name: Sudha Murty
Enter Price: 200
Enter Author name to count books: Salman Rushdie
Search successful
Number of books by Salman Rushdie : 2
Write a function Show_words() in python to read the content of a text file 'NOTES.TXT' and display only such lines of the file which have exactly 5 words in them.
Example, if the file contains :
This is a sample file.
The file contains many sentences.
But need only sentences which have only 5 words.
Then the function should display the output as :
This is a sample file.
The file contains many sentences.
The file "NOTES.TXT" contains:
This is a sample file.
The file contains many sentences.
But need only sentences which have only 5 words.
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')
This is a sample file.
The file contains many sentences.
Let "example.csv" file contain the following data:
Name Age Gender
Kavya 25 Female
Kunal 30 Male
Nisha 28 Female
import csv
with open("example.csv", 'r', newline='') as file:
reader = csv.reader(file, delimiter='\t')
for row in reader:
print(row)
['Name Age Gender']
['Kavya 25 Female']
['Kunal 30 Male']
['Nisha 28 Female']
import csv
def write_nested_list(data, file_name):
with open(file_name, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
def read_csv(file_name):
with open(file_name, 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
nested_list = [['Name', 'Age', 'Gender'],
['Prateek', '14', 'Male'],
['Ananya', '24', 'Female'],
['Aryan', '44', 'Male']]
write_nested_list(nested_list, 'output.csv')
print("Content of 'output.csv':")
read_csv('output.csv')
['Name', 'Age', 'Gender']
['Prateek', '14', 'Male']
['Ananya', '24', 'Female']
['Aryan', '44', 'Male']
Let "original.csv" file contain the following data:
Product,Price,Quantity
Apple,1.99,100
Banana,0.99,150
Orange,2.49,80
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)
with open(output_file, 'w', newline='') as f_out:
writer = csv.writer(f_out, delimiter = output_delimiter)
writer.writerows(data)
change_delimiter('original.csv', 'modified.csv', ',', '|')
Contents of "modified.csv":
Product|Price|Quantity
Apple|1.99|100
Banana|0.99|150
Orange|2.49|80
Let "input.csv" file contain the following data:
check1,10,A
check2,20,B
data1,30,C
check3,40,D
data2,50,E
import csv
def filter(input_file, output_file):
with open(input_file, 'r', newline='') as f_in, open(output_file, 'w', newline='') as f_out:
reader = csv.reader(f_in)
writer = csv.writer(f_out)
for row in reader:
if not row[0].startswith('check'):
writer.writerow(row)
filter('input.csv', 'output.csv')
Contents of "output.csv":
data1,30,C
data2,50,E
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 :
(a) add(). To accept and add data of an employee to a CSV file 'furdata.csv'. Each record consists of a list with field elements as fid, fname and fprice to store furniture id, furniture name and furniture price respectively.
(b) search(). To display the records of the furniture whose price is more than 10000.
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():
with open('furdata.csv', mode='a', newline='') as file:
writer = csv.writer(file)
fid = input("Enter furniture id: ")
fname = input("Enter furniture name: ")
fprice = float(input("Enter furniture price: "))
writer.writerow([fid, fname, fprice])
print("Record added successfully to 'furdata.csv'")
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()
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