0% found this document useful (0 votes)
41 views44 pages

FileHandling - ComputerNetworks Support Material

The document provides an overview of data file handling, focusing on text files and their characteristics, including types, modes of access, and methods for reading and writing data. It explains the differences between text and binary files, outlines the steps for processing text files in Python, and discusses file operations such as opening, closing, and manipulating file pointers. Additionally, it includes multiple choice questions, assertions, and short answer type questions related to file handling in Python.

Uploaded by

mitha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views44 pages

FileHandling - ComputerNetworks Support Material

The document provides an overview of data file handling, focusing on text files and their characteristics, including types, modes of access, and methods for reading and writing data. It explains the differences between text and binary files, outlines the steps for processing text files in Python, and discusses file operations such as opening, closing, and manipulating file pointers. Additionally, it includes multiple choice questions, assertions, and short answer type questions related to file handling in Python.

Uploaded by

mitha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DATA FILE HANDLING

TEXT FILE

• A file is a collection of data stored on a storage device.


• Used to store data permanently for later use.
• Files can be read from and written to using programming languages like Python, C++, Java, etc.
Types of Files
1. Text Files

Store data in readable characters (ASCII or Unicode).

Extensions: .txt, .py, .html

Can be opened and edited with any text editor.
• CSV Files (Comma-Separated Values)
• Special type of text files that stores tabular data.
• Each line represents a row; values separated by commas.
• Extension: .csv
• Easily used with spreadsheet tools and data processing libraries.
2. Binary Files
• Store data in binary (0s and 1s).
• Not human-readable.
• Extensions: .exe, .jpg, .dat

Used for images, audio, video, and compiled programs.
NOTE: A text file can be understood as a sequence of characters consisting of alphabets, numbers and
other special symbols. Files with extensions like .txt, .py, .csv, etc. are some examples of text files.

30 | P a g e
✔ While opening a text file, the text editor translates each ASCII value and shows us the equivalent
character that is readable by the human being.
✔ Each line of a text file is terminated by a special character, called the End of Line (EOL). For
example, the default EOL character in Python is the newline (\n).

Steps to Process Text Files:


To open a file in Python, we use the open ( ) function. The syntax of open ( ) is as follows:
file_object= open (file_name, access_mode)
ex1. Fobj= open('[Link],'w')
ex2. Fobj= open('D:\\Computer\\[Link]’, 'w') #double slash should be used in file path
ex3. Fobj= open(r'D:\Computer\[Link], 'w') #if you don’t want to use // then use r in front of file

Note: if file mode is not mentioned in open function, then default file mode, 'r' is used

File Open Modes


File Mode Description File Offset position
<r> Opens the file in read-only mode. Beginning of the file
<rb> Opens the file in binary and read-only mode. Beginning of the file
<r+> Opens the file in both read and write mode. Beginning of the file
<w> Opens the file in write mode. If the file already exists, all Beginning of the file
the contents will be overwritten. If the file doesn’t exist,
then a new file will be created.
<wb> Opens the file in binary and write mode. If the file already Beginning of the file
exists, all the contents will be overwritten. If the file
doesn’t exist, then a new file will be created.
<wb+> Opens the file in read, write and binary mode. If the file Beginning of the file
already exists, the contents will be overwritten. If the file
doesn’t exist, then a new file will be created.
<a> Opens the file in append mode. If the file doesn’t exist, End of the file
then a new file will be created.
<a+> Opens the file in append and read mode. If the file doesn’t End of the file
exist, then it will create a new file.

Use of With Clause


Syntax:
with open (“file name”, access mode) as file object:
example: with open(“[Link]”, ’r’) as f:
NOTE: No need to close the file explicitly if we are using with clause

31 | P a g e
Closing a file
• Once done with the read/write operations on a file, close the file.
• Python provides a close ( ) method to do so.
• While closing a file, the system frees the memory allocated to it.
• The syntax of close ( ) is:
file_object.close( )

Writing to a Text File


• For writing to a file, open it in write or append mode.
• If we open an existing file in write mode, the previous data will be erased, and the file object will
be positioned at the beginning of the file.
• On the other hand, in append mode, new data will be added at the end of the previous data as the
file object is at the end of the file.
• After opening the file, we can use the following methods to write data in the file.
• write ( ) - for writing a single string
• writelines( ) - for writing a sequence of strings
Example 1:
with open ("[Link]", "w") as f:
[Link]("Hello World\n")
[Link]("This is a second line.\n")
#You need to manually add \n if you want line breaks.
Example 2:
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open ("sample_lines.txt", "w") as f:
[Link](lines)
#It does not add newlines automatically – include \n in each string if needed.

Reading from a Text File


• Before reading a file, we must make sure that the file is opened in “r”, “r+”, “w+” or “a+” mode.
• There are three ways to read the contents of a file:
read ( ) readline( ) readlines( )

Reads the entire file as one string Reads one line at a time Reads all lines into a list of strings

Use when you want to load the Call multiple times to read useful for looping through lines
whole file at once multiple lines

[Link]( ) [Link]( ) [Link]( )


Output Output Output
"Hello\nWorld\nPython" "Hello\n" ["Hello\n","World\n", Python"]

to read a specified number of used to read a specified using readlines( ) function, lines in the
bytes use number (n) of bytes of data file become members of a list, where
[Link](n) from a file but maximum up each list element ends with a newline
to the newline character character (‘\n’)
(\n)
[Link](n)

32 | P a g e
SETTING OFFSETS IN A FILE
• The tell ( ) method • The seek ( ) method

This function returns an integer that This method is used to position the file object at a
specifies the current position of the file particular position in a file.
object in the file.
The position specified is the byte position In the given syntax, offset is the number of bytes by
from the beginning of the file till the current which the file object is to be moved. reference_point
position of the file object. indicates the starting position of the file object.
That is, with reference to which position, the offset has
to be counted. It can have any of the following values:
0 - beginning of the file
1 - current position of the file
2 - end of file
The syntax of using tell ( ) is: The syntax of seek ( ) is:
file_object.tell( ) file_object.seek(offset [, reference_point])

RELATIVE AND ABSOLUTE PATH


Absolute Path:
• It gives the complete path to a file or folder from the root directory.
• Always starts from the drive name (Windows) or root “/” (Linux/Mac).
• Used when the exact location of the file is known.
Example: f = open ("C:/Users/John/Documents/[Link]", "r")
Relative Path:
• It gives the location relative to the current working directory (where your Python script is).
• Useful for portability across systems.
Example:
f = open ("files/[Link]", "r")
Special Notations:
. → Current directory
.. → Parent directory
# Access file in parent directory
f = open ("../[Link]", "r")
#To get current working directory
import os
print([Link]( ))

Multiple Choice Questions


1. What does the 'r' mode do when open a file in Python?
a) Opens a file for writing only b) Opens a file for reading only
c) Opens a file for appending d) Opens a file in binary mode
2. Which of the following functions changes the position of file pointer?
a. flush( ) b. tell( ) c. seek( ) d. offset( )
3. Which of the following function returns a list datatype?
a. d=[Link]( ) b. d=[Link](10) c. d=[Link]( ) d. d=[Link]( )

33 | P a g e
4. What will [Link]("Hello\nWorld") do in a text file?
a. Write the string without a newline b. Raise an error
c. Write "Hello World" on a single line d. Write "Hello" and "World" on separate lines
5. The correct syntax of seek( ) is:
a. file_object.seek(offset [, reference_point]) b. seek(offset [, reference_point])
c. seek(offset, file_object) d. seek.file_object(offset)
6. What will be the output of the following statement in python? (fh is a file handle)
[Link](-30,2)
Options:- It will place the file pointer:-
a. at 30th byte ahead of current file pointer position
b. at 30 bytes behind from end-of file
c. at 30th byte from the beginning of the file
d. at 5 bytes behind from end-of file.
7. Which Python function is used to open a text file for reading?
a. open ("[Link]", "w") b. open ("[Link]", "r")
c. read("[Link]") d. write("[Link]")
8. Text file [Link] is stored in the storage device. Identify the correct option out of the
following options to open the file in read mode.
i. myfile = open('[Link]','rb')
ii. myfile = open('[Link]','w')
iii. myfile = open('[Link]','r')
iv. myfile = open('[Link]')
a. only i b. both i and iv c. both iii and iv d. both i and iii
9. What is the correct way to ensure a file is automatically closed after reading?
a) [Link]( ) b) with open('[Link]') as file:
c) open('[Link]').close( ) d) read([Link])
10. State True or False.
The writelines( ) method automatically adds newline characters (\n) after each line.
ANSWERS:
1 b) Opens a file for reading only 2 c) seek( )
3 d) [Link]( ) 4 d) Write "Hello" and "World" on
separate lines
5 a) file_object.seek(offset [, reference_point]) 6 b) at 30 bytes behind from end-of file
7 b) open("[Link]", "r") 8 c) both iii and iv
9 b) with open('[Link]') as file: 10 False
ASSERTION (A) and REASONING (R)
Mark the correct choice as
(a) Both (A) and (R) are true and (R) is the correct explanation for (A).
(b) Both (A) and (R) are true and (R) is not the correct explanation for (A).
(c) (A) is true but (R) is false.
(d) (A) is false but(R) is true.
1. Assertion (A): Opening a file in 'a' mode will delete its previous content.
Reason (R): The 'a' mode appends new data at the end of the existing file content.
2. Assertion (A): The with statement ensures a file is properly closed after its block finishes.
Reason (R): Using with avoids the need to explicitly call close ( ) on a file object.
3. Assertion (A): Files must be closed using the close ( ) function to ensure data is saved properly.
Reason (R): Not closing a file may result in data loss or corruption
34 | P a g e
4. Assertion (A): Opening a file in write mode(‘w’) will delete its existing contents.
Reason (R): In Python, the ‘w’ mode creates a new file if it doesn't exist, but preserves old
content if the file exists.
5. Assertion (A): The writelines( ) method adds newline characters automatically after each line.
Reason (R): writelines( ) writes a list of strings.
Answers
1 (a) Both (A) and (R) are true and (R) is the correct explanation for (A).
2 (d) (A) is false but(R) is true.
3 (a)Both A and R are true, and R is the correct explanation of A.
4 (c)A is true, R is false.
5 (d) A is false, R is true
Short Answer Type Questions
1. Display words longer than 5 characters from [Link]
2. Write a function in Python that counts the number of “the” or “this” words present in a text
file “[Link]”.
Example: If the “[Link]” contents are as follows:
This is my first class on Computer Science. File handling is the easiest topic for me and
Computer Networking is the most interesting one.
The output of the function should be: Count of the/this in file
3. Write a Python program to count all the line having 'a' as last character.
4. Observe the following code and answer the questions that follow.
File=open(“MyData”,”a”)
_____________ #Blank1
[Link]( )
a) What type (text/binary) of file is MyData ?
b) Fill the Blank1 with statement to write “ABC” in the file “Mydata”
5. What does the split( ) function do when used on a line read from a text file? Explain with
example.
Answers
1 #Display words longer than 5 characters from [Link]
f=open("[Link]", "r")
lines = [Link]( )
for line in lines:
for word in [Link]( ):
if len(word) > 5:
print(word)
2 def displayTheThis( ):
num=0
f=open("[Link]","r") N=[Link]( ) M=[Link]( )
for x in M:
if x=="the" or x== "this":
print(x)
num=num+1
[Link]( )
print ("Count of the/this in file:",num)
3 #Number of lines having 'a' as last character
count =0
35 | P a g e
f=open('[Link]',"r")
data=[Link]( )
for line in data:
if line[-2] == 'a':
count=count+1
print("Number of lines having 'a' as last character is/are : " ,count)
[Link]( )
4 a) Text File b) [Link](“ABC”)
5 The split ( ) function breaks a string into a list of words using whitespace as the default
separator.
line = "Hello world"
print([Link]( ))
output
['Hello', 'world']
Long Answer Type Questions
1. Program to count number of “ME” or “MY” in a text file [Link]
Ans #Program to count number of "ME" or "MY" in a text file [Link]
def countwords( ):
f=open("D:\\xiic\\[Link]","r")
count=0
1st=[Link]( )
for i in [Link]( ):
if [Link]( )=="Me".upper ( ) or [Link] ( )=="My".upper( ):
count=count+1
print ("Number of me or my is", count)
[Link]( )
countwords( )
2. Program to count number of “a” or “m” in a text file [Link]
Ans # def countAM( ):
f=open("D:\\xiic\\[Link]","r"}
countA=0
countM=0
CON=[Link]( )
for i in CON:
if [Link]( )=='A':
countA=countA+1
elif [Link]( ) == 'M':
countM=countM+1
print ("Number of A is ", countA, "\nNumber M is:", countM)
[Link]( )
countAM ( )
3 Program to count number of lines starting with “M”
Ans #Program to count number of lines starting with “M”
def countlines( ):
f=open("D:\\xiic\\[Link]","r")

36 | P a g e
count1=0
LN=[Link]( )
for i in LN:
If i[0]=="M":
count1+=1
print("Number of lines starting with M=", count1)
[Link]( )
countlines ( )
4 Program to print lines not staring with a vowel from a text file [Link]
Ans #Program to print lines not staring with a vowel from a text file [Link]
def COUNTLINES( ):
file lines
count=0
open ('D:\\XIIC\\[Link]', 'r') [Link] ( )
for w in lines:
if (w[0]).lower( ) not in 'aeoiu':
count count + 1
print ("The number of lines not starting with any vowel: ", count)
[Link]( )
COUNTLINES( )
5 Write a function ETCount( ) in Python, which should read each character of a text file
“[Link]” and then count and display the count of occurrence of alphabets E and T
individually (including small cases e and t too)
Ans #Write a function ETCount( ) in Python, which should read each character of a tex
def ETCount( ):
file open ('D:\\XIIC\[Link]', 'r')
lines=[Link]( )
countE=0
countT=0
for ch in lines:
if ch in 'Ee':
countEcountE + 1
if ch in 'Tt':
countT-countT+ 1
print ("The number of E or e: ", countE) print ("The number of T or t : ", countT)
[Link]( )
ETCount( )
6 Program to count the word “AND” in a text file [Link]
Ans #Program to count the word "AND" in a text file [Link].
def COUNT_AND( ):
count=0
file=open('D:\\XIIC\\[Link]', 'r')
line=[Link]( )
word=[Link]( )
for w in word:
37 | P a g e
if w in ['AND', 'and', 'And']:
count=count+1
print ("Number of word And is", count)
[Link]( )
COUNT_AND ( )
7 Write a function in Pyton to read lines from a text file [Link], and display only those lines,
which are starting with an alphabet 'P'.
Ans #Write a function in Pyton to read lines from a text file [Link], and #display only those
lines, which are starting with an alphabet 'p'.
def rdlines( ):
file= open('D:\\XIIC\\[Link]','r')
lines=[Link] ( )
for line in lines:
if line[0] == 'p':
print (line)
[Link]( )
rdlines ( )
8 Program to remove lines starting with @ and write it into another file.
Ans def filter( ):
fin=open("d:\\xiic\\[Link]","r")
fout=open("d:\\xiic\\[Link]", "w")
text=[Link] ( )
for i in text:
if i[0]!="@":
[Link](i)
[Link]( )
[Link]( )
def showcontent ( ) :
fin=open("d:\\xiic\\[Link]","r"}
text=[Link]( )
print (text)
[Link]( )
filter( )
showcontent( )

BINARY FILE
A binary file is a file whose content is in a binary format (0s and 1s). It stores data as a sequence of bytes
(each byte = 8 bits). Binary files include a wide range of file types, including executables, libraries,
graphics, databases, archives and many others.
There are mainly two types of data files — text file and binary file.
Differences between text files and binary files.
S. No. Text file Binary File
1. The text files can easily be transferred Binary files cannot easily be transferred from
from one computer system to another. one computer system to another due to
variations.
38 | P a g e
2. It stores data using ASCII format i.e. It stores data in binary format i.e. with the help
human-readable graphic characters. of 0 and 1.
3. These files are easily readable and These files are not easily readable and
modifiable because the content written in modifiable because the content written in binary
text files is human readable. files is not human-readable and it is encrypted
content.
Steps to process a binary file
• Opening a file
• Writing data into a file
• Reading data from a file
• Closing a file
Opening a Binary file in Python
Opening a file refers to getting the file ready either for reading or for writing.
To open a file in Python, we use the open ( ) function.

The syntax of open ( ) is as follows:

<file_object>= open (<file_name>, <access_mode>)

Closing a Binary file


Python has a close( ) method to close a file.
The syntax of close ( ) is as follows:
<file_object>.close( )
FILE MODES:
Mode Description
rb Open file in binary mode for reading only. The file pointer stands at the beginning of
the file. Gives error if file does not exist
rb+(r+b) Open file in binary mode for both reading and writing. The file pointer stands at the
beginning of the file. Gives error if file does not exist
wb Open file in binary mode for writing only. It creates the file if it does not exist. If the
file exists, then it erases all the contents of the file. The file pointer stands at the
beginning of the file.
wb+(w+b) Open file in binary mode for both reading and writing. It creates the file if it does not
exist. If the file exists, then it erases all the contents of the file. The file pointer stands
at the beginning of the file.
ab Open file in binary mode for appending data. Data is added to the end of the file. It
creates the file if it does not exist. The file pointer stands at the end of the file.
ab+(a+b) Open a file in binary mode for reading and appending data. Data is added to the end
of the file. It creates the file if it does not exist. The file pointer stands at the end of
the file.
Import pickle Module in Python
To write data to a binary file and read it subsequently, we need to use the Python module pickle.
The module pickle is used for serializing and de-serializing any Python object structure

39 | P a g e
Pickling/Serialization: The process of converting the structure (lists and dictionary etc.) into a byte
stream just before writing to the file.
Unpickling/De-serialization: The reverse of pickling process where information from byte stream gets
converted into object structure.

Structure Pickling Byte Stream

Methods of pickle module:


1. [Link]( ): Used to pickle the data object into byte stream and stores it in the binary file.
Syntax
[Link](object , file_object) - used to write any object to the binary file.
2. [Link]( ) : Used to read data from a binary file. It converts the binary data back into the
original python object (like a list, dictionary etc.).
Syntax
object=[Link](file_object) - used to read object from the binary file.

Writing data into a Binary File


Example:
import pickle
f=open("[Link]","wb")
x="Hello 1"
[Link](x,f) # writing a string to file
x=[1,2,3,4,5]
[Link](x,f) #writing a list to file
x={"Name":"Ajay","Age":15,"Class":9}
[Link](x, f) # writing a Dictionary to file
[Link]( )
Reading data from a Binary file
Follow these steps to read data:
1. Open the file in read mode using “rb” Ex.: f = open (“[Link]”, “rb”)
2. Use while loop with True statement to read the entire contents of the file individually.
3. Use try – except for Exception handling to handle runtime EOFError
4. Now load data into an object through the load( ) function
5. Print data as per need
6. Close the file
Example:
import pickle
f=open("[Link]",'wb+') # This will open the file in write and read mode
x=[1,2,3,4,5]
[Link](x,f) # This will write the object List into the file.
[Link](0) #This will move the file pointer to the begining of the file
x=[Link](f) #This will read the object from the file and store in variable.
print(x)
Search records from binary file
Follow these steps to search the record in the binary file:
1. Open the file in reading mode using “rb”
2. Prompt a message to ask unique field from data to search
40 | P a g e
3. Declare a boolean variable flag to store False for the record not found and True when the record
found
4. Use a while loop to access records individually
5. Now load the data into the dictionary object using load( ) function
6. Use if condition to compare the data with the variable taken in step 2
7. Print the record found
8. Assign True to the flag variable declared in step 3
9. Use the except block to handle EOFError and terminate the loop using the break
10. Print record not found message when Flag is False
11. Finally, close the file using [Link]( )
Example:
import pickle
def bf_search( ):
try:
f=open("[Link]","rb")
pc=int(input("Player code to search:")) flag=False
while True:
try:
rec= [Link](f)
if rec['Pcode']==pc:
print("Player Name:",rec['Pname'])
print("Individual Score:",rec['Score'])
print("Rank:",rec['Rank'])
flag = True
except Exception:
break
except FileNotFoundError:
print("The file [Link] does not exist")
if flag==False:
print("Record not found...")
[Link]( )
bf_search( )

Append data in Binary File


To append data in binary follow these steps:
1. Open the file in append mode using “ab” Ex.: f = open (“[Link]”,”ab”)
2. Enter data to append
3. Append entered data into the dictionary/list object
4. Use [Link]( ) method to write the dictionary/list data
5. Close the file
Example:
def bf_append( ):
import pickle
f=open("[Link]","ab")
print("Append Data")
pcode=int(input("Enter the Player code:"))
pname = input("Enter Player Name: ")
score =int(input("Enter individual score:"))
41 | P a g e
rank =int(input("Enter Player Rank:"))
rec={'Pcode':pcode,'Pname':pname,'Score':score,'Rank':rank}
[Link](rec,f)
[Link]( )
bf_append( )

Update record in Binary file


To update record, you can use the search record code if you wish. To update the record follow these
steps:
1. Open the file using read mode
2. Declare a variable for unique value to be updated
3. Use try-except and while loop as explained above
4. Add record fetched from binary file into a list
5. Enter the new record information to update
6. Compare the fetched records with entered record and assign the new values to update
7. Write the data using dump( ) function
8. Close the file
Example:
def bf_update( ):
import pickle
f=open('[Link]','rb')
reclst=[]
wihile True:
try :
rec = [Link](f)
[Link] (rec)
except EOFError:
break
[Link]( )
pc=int(input("Enter player code to update:")
pn=input("Enter new name:")
ps=int(input("Enter Player Score:"))
pr=int(input("Enter Player Rank:"))
for i in range (len(reclst)):
if reclst[i] Pcode =pc:
reclst[i]['Pname'] = pn
reclst[i]['Score']= ps
reclst[i]['Rank']=pr
f=open('[Link]','wb')
for i in reclst:
[Link](i,f)
[Link]( )
bf_update( )
Multiple choice Questions
1. Which file mode can be used to open a binary file in both append and read mode?
a) w+ b) wb+ c) ab+ d) a+

42 | P a g e
2. Nila wants to store a list of dictionaries into a binary file. Which of the following Python
modules should she use?
a) os b) csv c) pickle d) json
3. Pick the correct syntax to read a binary file using pickle:
a) [Link](file) b) [Link](file)
c) [Link](file) d) [Link](file)
4. What does the [Link](obj, file) function do?
a) Reads binary data from a file
b) Writes text data to a file
c) Converts a Python object into byte stream and writes it to a file
d) Appends an object to a list
5. Which file mode should be used to write a binary file in Python?
a) 'w' b) 'r' c) 'wb' d) 'rb'
6. What will happen if you try to read a binary file using 'r' mode instead of 'rb'?
a) It will read data correctly.
b) It will raise a SyntaxError.
c) It will convert binary data into text
d) It may raise an error or return incorrect data
7. Which of the following is a key advantage of binary files over text files?
a) Easy to read with any text editor
b) Allows direct storage of complex Python objects
b) Consumes more storage space
d) Cannot be shared across system
Answers :

1 C 2 C 3 B 4 C
5 C 6 D 7 B

Assertion and Reasoning


Mark the correct choice as:
a) Both A and R are true, and R is the correct explanation of A.
b) Both A and R are true, but R is not the correct explanation of A.
c) A is true, but R is false.
d) A is false, but R is true.
1. Assertion (A): A binary file in python is used to store collection objects like lists and
dictionaries that can be later retrieved in their original form using pickle module.
Reasoning (A): A binary files are just like normal text files and can be read using a text editor
like notepad
2. Assertion (A): The pickle module in Python is used to store and retrieve Python objects in
binary files.
Reason (R): The [Link]( ) method reads data from a binary file and the [Link]( )
method writes data to a binary file.
3. Assertion (A): Binary files are used to store data in the same format as it is stored in
memory.
Reason (R): Binary files convert Python objects into byte streams which are machine-
readable.
43 | P a g e
4.
Assertion (A): You can open a binary file using only 'r' or 'w' mode in Python.
Reason (R): Binary files should be opened with 'rb' or 'wb' modes to ensure correct handling
of byte streams.
5. Assertion (A): Binary files are preferred when large volumes of data need to be stored with
structure.
Reason (R): Binary files are human-readable and can be opened using any text editor.
Answers:
1 C 2 C 3 A 4 D
5 C

Short Answer Type Questions:


1 What is the purpose of the pickle module in Python?
2 State two advantages of using binary files over text files in Python.
3 How many times should [Link]( ) be called while reading a binary file?
Explain your answer with reference to the number of times [Link]( ) was used while
writing the file.
Answers :
1 The pickle module is used for serializing and de-serializing Python objects into binary
format.
It allows saving complex data types like dictionaries, lists, etc., into a binary file and
retrieving them later.
2 Binary files can store complex Python objects (like dictionaries, lists) directly.
They are more secure and efficient in terms of storage space and speed.
3 The number of times [Link]( ) should be called is equal to the number of times
[Link]( ) was called when the file was written.
If the file was written using [Link]( ) 3 times, then you must call [Link]( ) 3 times to
read all the data.
Since we may not know the exact count, load( ) is usually called inside a loop until EOFError
occurs.
Long Answer Type Questions:
1. Karthik is a manager working in a recruitment agency. He needs to manage the records of
various candidates. For this, he wants the following information of each candidate to be
stored:
Candidate_ID – integer
Candidate_Name – string
Designation – string
Experience – float
You, as a programmer of the company, have been assigned to do this job for Karthik.
i. Write a function to input the data of a candidates and append it in a binary file
ii. Write a function to update the data of candidates whose experience is less than 10
years and change their designation to "Assistant Manager".
iii. Write a function to read the data from the binary file and display the data of all those
candidates who are not "Assistant Manager".
Ans import pickle
1(i) def input_candidates( ):
44 | P a g e
f=open("[Link]","ab")
n = int(input("Enter the number of candidates you want to add: "))
for i in range(n):
candidate_id = Candidate ID: "))
candidate_name = input("Enter Candidate Name: ")
designation = input("Enter Designation: ")
experience = float(input("Enter Experience (in years):")):
[Link]([candidate_id, candidate_name, designation, experience],f)
print("Candidate data appended successfully. ")
(ii) import pickle
def update_assistant_manager( ):
updated_candidates = []
try:
with open('[Link]', 'rb') as file:
while True:
try:
Candidate= [Link](file)
if candidate[3] < 10: # If experience <10 years
candidate[2] = 'Assistant Manager'
updated_candidates.append(candidate)
except EOFError:
break # End of file reached
except FileNotFoundError:
print("No candidate data found. Please add candidates first")
with open('[Link]', 'wb') as file:
for candidate in updated_candidates:
[Link](candidate, file)
1(iii) import pickle
def display_non_assistant_managers( ):
try:
with open('[Link]', 'rb') as file:
while True:
try:
candidate [Link](file)
if candidate[2] != 'Assistant Manager':# Check if not Assistant Manager
print("Candidate ID: ",candidate[0])
print("Candidate Name:",candidate[1])
print("Designation:",candidate[2])
print("Experience:",candidate[3])
print("________________")
except EOFError:
break # End of file reached
except FileNotFoundError:
print("candidate data found. Please add candidates first.")
2 A school is maintaining student records in a binary file [Link]. Each record stores the
following data:
Roll Number (int)
Name (str)
45 | P a g e
Percentage Marks (float)
Write Python functions to do the following
i. Create a binary file by entering student data in the form of dictionaries.
ii. Count and display the number of students who scored less than 40% (i.e., need
academic improvement).
Ans import pickle
2(i) def create_file( ):
with open('[Link]', 'wb') as file:
n = int(input("Enter number of students:"))
for I in range(n):
student = {}
student['roll'] = int(input("Enter Roll No:"))
student['name'] =input("Enter Name:")
student['percentage'] = float(input("Enter Percentage:"))
[Link](student, file)
2(ii) import pickle
def count_low_score( ):
count = 0
try:
with open('[Link]', 'rb') as file:
while True:
try:
student = [Link](file)
if student['percentage'] < 40:
Count+= 1
except EOFError:
break
print("Number of students with less than 40% marks:", count)
except FileNotFoundError:
print("File not found!")
3 A binary file [Link] contains records of books. Each record is stored as a dictionary with
the following fields:
bid- (Book ID – integer)
title- (Book Title – string)
price- (Book Price – float)
The librarian wants to perform the following operations efficiently:
i. Define a function add_books(n) that adds n book records to the binary file.
ii. Define a function update_price(Bid, new_price) that updates the price of the book
whose Book ID is Bid.
iii. Define a function count_books_in_range(low, high) that returns the number of books
whose price lies between low and high (inclusive).
3(i) import pickle
def add_books(n):
with open("[Link]","ab") as f:
for i in range(n):
book ={}
book['bid'] int(input("Enter Book ID:")
book['title'] = (input("Book Title:")
46 | P a g e
book['price'] = float(input("Enter Book Price: "))
[Link](book, f)
(ii) import pickle
def update_price(Bid, new_price):
updated = False
temp_list =[]
try:
with open("[Link]", "rb") as f:
while True:
try:
book = [Link](f)
if book['bid'] == Bid:
book['price'] = new_price
updated = True
temp_list.append(book)
except EOFError:
break
with open("[Link]", "wb") as f:
for book in temp_list:
[Link](book, f)
if updated:
print("Price updated successfully.")
else:
print("Book ID not found.")
except FileNotFoundError:
print("File not found.")
(iii) import pickle
def count_books_in_range(low,high):
count = 0
try:
with open("[Link]","rb") as f:
while True:
try:
book = [Link](f)
if low <=book['price'] <=high:
count +=1
except EOFError:
break
print("Total books priced between",low,"and",high,":",count)
except FileNotFoundError:
print("File not found.")
4. A binary file [Link] stores records of patients in a hospital. Each record is stored as a
dictionary with the following fields:
pid- (Patient ID – integer)
pname- (Patient Name – string)
age- (integer)
bill- (float – hospital bill amount)
Perform the following tasks using three user-defined functions:
47 | P a g e
i. Define a function add_patients(n) to add n new patient records to [Link].
ii. Define a function update_bill(Pid, amount) that updates the bill of a patient by adding
the given amount to the existing bill using their Patient ID.
iii. Define a function list_senior_patients( ) to display details of all patients aged 60 and
above.
Ans import pickle
4(i) def add_patients(n):
with open("[Link]", "ab") as f:
for i in range(n):
patient = {}
patient['pid'] = int(input("Enter Patient ID: "))
patient['pname'] = input("Enter Patient Name: ")
patient['age'] = int(input("Enter Age: "))
patient['bill'] = float(input("Enter Bill Amount: "))
[Link](patient, f)
4(ii) import pickle
def update_bill(Pid, amount):
updated = False
patients = []
try:
with open("[Link]", "rb") as f:
while True:
try:
patient = [Link](f)
if patient['pid'] == Pid:
patient['bill'] += amount
updated = True
[Link](patient)
except EOFError:
break
with open("[Link]", "wb") as f:
for p in patients:
[Link](p, f)
if updated:
print("Bill updated successfully.")
else:
print("Patient ID not found.")
except FileNotFoundError:
print("File not found.")
4(iii) import pickle
def list_senior_patients( ):
try:
with open("[Link]", "rb") as f:
print("Senior Patients (Age 60+):")
found = False
while True:
try:
patient = [Link](f)
48 | P a g e
if patient['age'] >= 60:
print(patient)
found = True
except EOFError:
break
if not found:
print("No senior patients found.")
except FileNotFoundError:
print("File not found.")
5. A binary file, [Link] has the following structure : [Emp_Id, Name, Salary] where
Emp_Id : Employee id
Name: Employee Name
Salary: Employee Salary
Write a user defined function, disp_Detail( ), that would read the contents of the file
[Link] and display the details of those employees whose salary is below 25000.
Ans import pickle
def Copy_new( ):
F2=open("new_items.dat", "wb")
try:
F1=open("[Link]","rb")
Datal=[Link](F1)
Data2={}
for K,V in [Link]( ):
if v[1]>1000:
Data2 [K]=V
[Link] (Data2, F2)
[Link]( )
except:
print("File not found!")
[Link]( )
6. Mr. Ashok is working on a Toy Shop project to manage toys records using Python. The toys
data is stored in a binary file named [Link]. The binary file [Link] contains
each record in given format:
{“Toy_ID”: T_ID, “TName”:toy_name, “Price”:price}
Where
● Toy_ID: Toy ID (string)
● TName: Toy name (string)
● Price: Price of toy (integer)
You as a programmer, help him to write following python functions:
i. ADD_Data( ) : To write n records in binary file [Link] by taking the values
for each record from user.
ii. SHOW_Data( ) : Read all records from binary file and display them.
iii. Remove_Toy( ) : that deletes the record of a toy in the file [Link] based on
the Toy ID provided by the user. If the Toy ID does not exist in the file, display an
appropriate message.
Ans import pickle
6(i) def ADD_Data( ):
f=open("[Link]", "wb")
49 | P a g e
L=[ ]
n=int(input("How many records you want to enter: "))
for i in range(n):
T_ID=input("Enter Toy ID: ")
toy_name=input("Enter Toy Name: ")
price=int(input("Enter Price: "))
D={"Toy_ID":T ID, "TName": toy name, "Price":price}
[Link](D)
[Link](Lf)
[Link]( )
6(ii) def SHOW_Data( ):
f=open("[Link]", "rb")
L=[Link](f)
print(L)
[Link]( )
6(iii) def Remove_Toy( ):
Toy_ID=input("Enter Toy ID: ")
f=open("[Link]", "rb+")
found=0
L=[Link](f)
M=[ ]
for D in L:
if Toy ID not in D["Toy_ID"]:
[Link](D)
else:
found=1
if found==1:
[Link](0)
[Link](M,f)
print("Record Deleted successfully")
else:
print("Record not found")
[Link]( )
7. A file, [Link], stores the records of passengers using the following structure :
[PNR, PName, BRDSTN, DESTN, FARE]
where :
PNR – Passenger Number (string type)
PName – Passenger Name (string type)
BRDSTN – Boarding Station Name (string type)
DESTN – Destination Station Name (string type)
FARE – Fare amount for the journey (float type)
Write user defined functions in Python for the following tasks :
(i) Create( ) – to input data for passengers and write it in the binary file [Link].
(ii) SearchDestn(D) –to read contents from the file [Link] and display the details
of those Passengers whose DESTN matches with the value of D.
(iii) UpdateFare( ) – to increase the fare of all passengers by 5% and rewrite the updated
records into the file [Link].
Ans import pickle
50 | P a g e
7(i) def Create( ):
F=open ("[Link]", "wb")
PNR=input("PNR No: ")
PName=input("Name: ")
BRDSTN=input ("Boarding at: ")
DESTN=input("Destination: ")
FARE=float(input("Fare: "))
Rec= [PNR, PName, BRDSTN, DESTN, FARE]
[Link] (Rec, F)
[Link]( )
7(ii) def SearchDestn (D):
try:
F=open ("[Link]", "rb")
Rec=[Link](F)
for R in Rec:
if R[3]==D;
print (R)
[Link]( )
except:
print("File not found!")
7(iii) def UpdateFare( ):
try:
FR=open ("[Link]", "rb+")
Rec=[Link](FR)
for I in range (len (Rec)):
Rec [1] [4] += (Rec [I] [4] * 0.05)
print("Updation Done!")
[Link](0)
[Link] (Rec, FR)
[Link]( )
except:
print("File not found!")
8. Consider a binary file, [Link] containing information in the following structure :
[Mno, Mname, Mtype]
Write a function, search_copy( ), that reads the content from the file [Link] and copies
all the details of the "Comedy" movie type to file named [Link].
Ans import pickle
def search_copy( ):
try:
F1=open("[Link]","rb")
F2=open("[Link]", "wb")
Datal=[Link](F1)
Data2=[ ]
for D in Datal:
if D[2]=="Comedy":
[Link](D)
[Link] (Data2, F2)
[Link]( )
51 | P a g e
[Link]( )
except:
print("File not found!")
9. Consider a binary file, [Link], containing records stored in the given format : {item_id:
[item_name,amount]}
Write a function, Copy_new( ), that copies all records whose amount is greater than 1000
from [Link] to new_items.dat.
Ans import pickle
def Copy_new( ):
F2=open("new_items.dat", "wb")
try:
F1=open("[Link]","rb")
Datal=[Link](F1)
Data2={ }
for K,V in [Link]( ):
if v[1]>1000:
Data2 [K]=V
[Link] (Data2, F2)
[Link]( )
except:
print("File not found!")
[Link]( )

COMMA SEPARATED VALUES(CSV) FILES

52 | P a g e
CSV stands for Comma Separated Values CSV file is a type of plain text file means data stored in form of
ASCII or Unicode characters Each line is a row and in row each piece of data is separated by a comma It
is common format for data interchange.

Steps to Process CSV Files:


1. First of all we have to import csv module for file operation.
2. For writing to CSV Files ,
i. We open file in ‘w’ writing or ‘a’ append mode using open( ) method
f=open(‘[Link]’,’w’,newline=’ ’)
By setting newline='', Python don’t modify the newline characters at all. This is commonly used
when working with the csv module to ensure that the [Link] handles the newline characters
correctly (i.e., without adding extra blank lines between rows).
i. Creating a writer object, associated with the file object. The writer object allows you to write rows
of data into the file in CSV format. Through [Link]( ) method ,we create it.
w_obj=[Link](f)
ii. Perform writing operation (read data from user and write on to csv file)
writerow( ) used for writing single row
writerows( )used for writing multiple rows
3. For Reading from CSV File
i. Creating a reader object, associated with the file object we use [Link]( ) method. It Creates a CSV
reader object that can iterate over the rows of the file object.
r_obj=[Link](f)
ii. Perform reading operation (read data from csv file and display using python)
[Link] the file using close( ) method
[Link]( )

[Link]( ) The [Link]( ) function in Python is used to read data from a CSV (Comma
Separated Values) file. It is part of Python’s built-in csv module.
[Link](file_object, delimiter=',')
Parameters:
• file_object: A file object opened using open( ).
• delimiter: (Optional) Specifies the character used to separate fields. Default is
comma (,).
It returns an iterator that returns each row in the CSV file as a list of strings.
Example
import csv
with open('[Link]', 'r') as file:
reader = [Link](file)
for row in reader:
print(row)
[Link]( ) The [Link]( ) function in Python is used to write data to a CSV file. It is part of
Python’s built-in csv module and writes rows as comma-separated values.
[Link](file_object, delimiter=',')

53 | P a g e
Parameters:
• file_object: A file object opened in write ('w') or append ('a') mode.
• delimiter: (Optional) Character that separates values. Default is comma (,).
• It returns a writer object that lets you write rows (lists or tuples) to the CSV
file.
Common Methods:
• [Link](row) → Writes a single row.
• [Link](list_of_rows) → Writes multiple rows.
Example:
import csv
with open('[Link]', 'w', newline='') as file:
writer = [Link](file)
# Write header
[Link](['Name', 'Age', 'City'])
# Write multiple data rows
[Link]([['Alice', 23, 'Delhi'],['Bob', 30, 'Mumbai'] ])

Multiple Choice Questions


1. Syntax for opening [Link] file in write mode is
myfile = open("[Link]","w",newline='').
What is the importance of newline=''?
a. A newline gets added to the file b. Empty string gets appended to the first line.
c. Empty string gets appended to all lines. d. EOL translation is suppressed
2. Which of the following is not a function / method of csv module in Python?
a. read( ) b. reader( ) c. writer( ) d. writerow( )
3. A CSV file
a. is a text file b. can store images
c. is a type of python program d. is a Computer Software Validation file
4. What does the [Link]( ) function do?
a. Reads JSON files b. Reads CSV files row by row as lists
c. Converts CSV to a dictionary d. Writes to CSV files
5. What mode should be used to open a file for reading in CSV format?
a. 'w' b. 'x' c. 'r' d. 'rw'
6. What is the default delimiter in a CSV file?
a. Semicolon (;) b. Tab (\t) c. Pipe (|) d. Comma (,)
7. State True or False:
CSV file is also known as delimited text file which can be opened in Notepad and Spreadsheet
both.
8. Which of the following is not a correct way to open a CSV file for writing?
a. open('[Link]', 'r') b. open('[Link]', 'a')
c. open('[Link]', 'w') d. open('[Link]', 'rw')
9. Which method writes multiple rows at once in a CSV file?
a. writerows( ) b. writeall( )
c. write( ) d. writemultiple( )
10. When using the [Link]( ) object to read from a CSV file, what type of data structure is
each row of data represented as?
a) String b) Dictionary c) List d) Tuple
54 | P a g e
ANSWERS:
1 D 2 A 3 A 4 B 5 C
6 D 7 True 8 A 9 A 10 C

ASSERTION REASONING QUESTIONS.


Mark the correct choice as
(a) Both (A) and (R) are true and (R) is the correct explanation for (A).
(b) Both (A) and (R) are true and (R) is not the correct explanation for (A).
(c) (A) is true but (R) is false.
(d) (A) is false but(R) is true
1 Assertion (A) : CSV file is a human readable text file where each line has a number of fields,
separated by comma or some other delimiter.
Reason (R): writerow( ) method is used to write a single row in a CSV file.
2 Assertion (A): The [Link]( ) object returns each row as a list of strings.
Reason (R): The [Link]( ) reads the entire file content at once into memory
3 Assertion (A): [Link]( ) can be used to write data row by row into a CSV file.
Reason (R): writerow( ) method of the [Link] object writes a single row to the CSV file.
4 Assertion (A): The newline='' parameter is used while opening a CSV file in Python.
Reason (R): It helps prevent insertion of blank lines between rows on Windows systems.
5 Assertion (A): [Link](file) returns an object that can be used to read data from a CSV file.
Reason (R): [Link]( ) is used for writing data into CSV files.
ANSWERS:
1 Ans: (b) Both (A) and (R) are true and (R) is not the correct explanation for (A).
2 Answer: c) A is true but R is false
Explanation: [Link]( ) reads the file line by line (not all at once), and returns rows as lists.
3 Answer: a) Both A and R are true, and R is the correct explanation of A
4 Answer: a) Both A and R are true, and R is the correct explanation of A
5 Answer: d) A is false but R is true
Explanation: [Link]( ) is for writing, not reading.
Long Answer Questions
1. Write a Program in Python that defines and calls the following user defined functions:
(i) ADD( ) – To accept and add data of an employee to a CSV file ‘[Link]’. Each record
consists of a list with field elements as empid, name and salary to store employee id,
employee name and employee salary respectively.
(ii) COUNTR( ) – To count the number of records present in the CSV file named
‘[Link]’.
Ans import csv
1(i) def ADD( ):
f=open('[Link]','a')
wr=[Link](f)
eid=int(input("Enter Employee ID"))
name=input("Enter name of employee")
sal=float(input("enter salary"))
data=[eid,name,sal]
[Link](data)
ADD( )

55 | P a g e
1(ii) import csv
def COUNTR( ):
f=open('[Link]','r')
c=0
data=[Link](f)
for x in data:
c=c+1
print(c)
COUNTR( )
2. Create a function maxsalary( ) in Python to read all the records from an already existing file
[Link] which stores the records of various employees working in a department. Data is
stored under various fields as shown below:
E_code E_name Scale Salary
A01 Bijesh Mehra S4 65400
B02 Vikram Goel S3 60000
C09 Suraj Mehta S2 45300
Function should display the row where the salary is maximum.
Note: Assume that all employees have distinct salary.
Ans import csv
def maxsalary( ):
f=open('[Link]', 'r')
reader=[Link] (f)
skip_header = True
m= 0
for row in reader:
if skip_header:
skip_header = False
else:
if(int(row[3])>m):
m=int(row[3])
rec=row
print('Row with the highest salary: ', rec)
[Link]( )
maxsalary( )
3. A csv file "[Link]" contains the data of a survey. Each record of the file contains the
following data:
• Name of a country
• Population of the country
• Sample Size (Number of persons who participated in the survey in that country)
• Happy (Number of persons who accepted that they were Happy)
For example, a sample record of the file may be:
[‘Signiland’, 5673000, 5000, 3426]
Write the following Python functions to perform the specified operations on this file:

56 | P a g e
a) [10, 20, 30] b) [10, 20]
c) [20, 30] d ) Error
5. What happens if you call pop ( ) on an empty stack?
a) Returns None b) Raises IndexError
c) Returns -1 d) Does nothing
Answers
1. B 2. C 3. C 4. B 5. B

ASSERTION REASONING QUESTIONS.


Mark the correct choice as
(a) Both (A) and (R) are true and (R) is the correct explanation for (A).
(b) Both (A) and (R) are true and (R) is not the correct explanation for (A).
(c) (A) is true but (R) is false.
(d) (A) is false but(R) is true.
1. Assertion (A): In Python, a stack can be implemented using a list.
Reason (R): A stack is an ordered linear list of elements that works on the principle of First
In First Out (FIFO).
2. Assertion (A): A stack can be used to reverse the contents of a text file line by line.
Reason (R): In a stack, the last element inserted is the first to be removed (LIFO).
3. Assertion (A): Using a stack is an efficient method for checking matching brackets in a file
containing Python code.
Reason (R): Stack allows multiple ends for insertion and deletion of elements.
4. Assertion (A): A stack can be implemented using a list in Python to read a file and store each
word for later processing.
Reason (R): Lists in Python do not support push and pop operations.
Answers
1 C 2 A 3 C 4 C
Long Answer Questions
1. A dictionary, d_city contains the records in the following format: {state:city}
Define the following functions with the given specifications:
(i) push_city(d_city): It takes the dictionary as an argument and pushes all the cities in
the stack CITY whose states are of more than 4 characters.
(ii) pop_city( ): This function pops the cities and displays "Stack empty" when there are
no more cities in the stack.
Ans CITY=[ ]
1(i) def push_city(d_city):
for c in d_city:
if len(c) > 4:
[Link](d_city[c])
1(ii) def pop_city( ):
while CITY:

64 | P a g e
print([Link]( ))
else:
print("Stack empty")
2. Consider a list named Nums which contains random integers. Write the following user
defined functions in Python and perform the specified operations on a stack named
BigNums.
(i) PushBig( ): It checks every number from the list Nums and pushes all such numbers
which have 5 or more digits into the stack, BigNums.
(ii) PopBig( ): It pops the numbers from the stack, BigNums and displays them. The
function should also display "Stack Empty" when there are no more numbers left in the
stack.
For example: If the list Nums contains the following data:
Nums = [213, 10025, 167, 254923, 14, 1297653, 31498, 386, 92765]
Then on execution of PushBig( ), the stack BigNums should store:
[10025, 254923, 1297653, 31498, 92765]
And on execution of PopBig( ), the following output should be displayed:
92765
31498
1297653
254923
10025
Stack Empty
Ans def PushBig(Nums,BigNums):
for N in Nums:
if len(str(N)) >= 5:
[Link](N)
def PopBig(BigNums):
while BigNums:
print([Link]( ))
else:
print("Stack Empty")
3. A list contains following record of course details for a University:
[Course_name, Fees, Duration]
Write the following user defined functions to perform given operations on the stack
named 'Univ' :
(i) Push_element( ) - To push an object containing the Course_name, Fees and Duration
of a course, which has fees greater than 100000 to the stack.
(ii) Pop_element( ) - To pop the object from the stack and display it. Also, display
“Underflow” when there is no element in the stack.
For example:
If the lists of courses details are:

65 | P a g e
["MCA", 200000, 3]
["MBA", 500000, 2]
["BA", 100000, 3]
The stack should contain
["MBA", 500000, 2]
["MCA", 200000, 3]
Ans Univ=[]
def Push_element(Course):
for Rec in Course:
if Rec[1]>100000:
[Link](Rec)
def Pop_element( ):
while len(Univ)>0:
print([Link]( ))
else:
print("Underflow")
4. Write separate user defined functions for the following:
(i) PUSH(N) - This function accepts a list of names, N as parameter. It then pushes only
those names in the stack named OnlyA which contain the letter 'A'.
(ii) POPA(OnlyA) - This function pops each name from the stack OnlyA and displays it.
When the stack is empty, the message "EMPTY" is displayed.
For example :
If the names in the list N are
['ANKITA', 'NITISH', 'ANWAR', 'DIMPLE', 'HARKIRAT']
Then the stack OnlyA should store
['ANKITA', 'ANWAR', 'HARKIRAT']
And the output should be displayed as
HARKIRAT ANWAR ANKITA EMPTY
Ans OnlyA=[ ]
def PUSH(N):
for aName in N :
if 'A' in aName :
[Link](aName)
def POPA(OnlyA):
while OnlyA :
print([Link]( ), end=' ')
else :
print('EMPTY')
5. Write the following user defined functions:
(i) pushEven(N) - This function accepts a list of integers named N as parameter. It then
pushes only even numbers into the stack named EVEN.

66 | P a g e
(ii) popEven(EVEN) - This function pops each integer from the stack EVEN and displays
the popped value. When the stack is empty, the message "Stack Empty" is displayed.
For example:
If the list N contains:
[10,5,3,8,15,4]
Then the stack, EVEN should store
[10,8,4]
And the output should be
4 8 10 Stack Empty
Ans EVEN=[ ]
def pushEven(N):
for z in N :
if z%2==0 :
[Link](z)
def popEven(EVEN):
while EVEN :
print([Link]( ), end=' ')
else :
print('Stack Empty')
6. Write the definition of a user defined function PushNV(N) which accepts a list of strings in
the parameter N and pushes all strings which have no vowels present in it, into a list named
NoVowel.
Write a program in Python to input 5 Words and push them one by one into a list named
[Link] program should that use the function PushNV( ) to create a stack of words in the
list NoVowel so that it stores only those words which do not have any vowel present in it,
from the list [Link], pop each word from the list NoVowel and display the popped
word. When the stack is empty, display the message "EmptyStack".
Ans def PushNV(N):
for W in N :
for C in W :
if [Link]( ) in 'AEIOU':
break
else:
[Link](W)
All=[ ]
NoVowel=[ ]
for i in range(5) :
[Link](input('Enter a Word: '))
PushNV(All)
while NoVowel :
print([Link]( ), end=' ')
else :
print('EmptyStack')

67 | P a g e
UNIT 2
COMPUTER NETWORKS
Concept Map:

Network: A group of two or more similar things or people interconnected with each other is called
network. Examples are social network and mobile network
Computer Network: A Computer network is an interconnection among two or more computers or
computing devices. The advantages of computer networks are:
• Resource Sharing
• Collaborative Interaction
• Cost Saving
• Increased storage
• Time Saving

68 | P a g e
EVOLUTION OF NETWORK:
(I)ARPANET (Advanced Research Project Agency Network)
• It came into existence in 1960s
• A project for interconnecting, US department of defense with academic and research organization
across different places for scientific collaboration.
(II)NSFNET (National Science Foundation Networks)
• It came into existence in 1986
• It was the first large-scale implementation of Internet technologies in a complex environment of
many independently operated networks
(III) INTRANET
• It is a local or restricted communication system
• It is managed by a person or organization.
• Intranet users can avail services from internet but Internet user cannot access intranet directly
(IV) INTERNET
• It came into existence in 1960s
• It is known as Network of Networks
• A global computer network providing variety of information and communication facilities
consisting of interconnected networks using standardized communication protocols.
DATA COMMUNICATION TERMINOLOGIES
DATA: Data means information in digital form such as text, audio, video which is stored processed and
exchanged between digital devices like computer, mobile phones or laptop. Computers process the raw
data into meaningful information. Information is processed data.
COMMUNICATION: The exchange of information between two or more networked or interconnected
devices is called communication
COMPONENTS OF DATA COMMUNICATION
a) SENDER: Sender is a device which is capable of sending data over a communication network. In data
communication Sender is also called Source.
b) RECEIVER: Receiver is a device which is capable of receiving data over a communication network. In
data communication Receiver is also called Destination.
c) MESSAGE: message is the information being exchanged between a sender and a receiver over a
communication network.
d) COMMUNICATION MEDIUM: Communication medium is the path or channel through which the
information is moved from the sender to the receiver. A communication medium can be either
wired/guided or wireless/unguided.
e) PROTOCOLS: The set of standard rules which are followed in data communication are known as Data
Communication Protocols. All the communicating devices like sender receiver and other connected
devices in the network should follow these protocols.
Why Protocols are needed?
The communicating devices may be in different geographical areas. The speed of these devices may be
different. Also, the data transfer rates of different networks may be different. These complexities make
it necessary to have a common set of rules to ensure the secure communication of data. Some commonly
used Protocols in data communication are:
69 | P a g e
• Transmission Control Protocol (TCP)
• Internet Protocol (IP)
• File Transfer Protocol (FTP)
• Simple Mail Transport Protocol (SMTP)
• Hyper Text Transfer Protocol (HTTP)

MEASURING CAPACITY OF COMMUNICATION MEDIA


Capacity of a communication channel means the maximum quantity of signals that a communication
channel can carry. The capacity of a communication medium is measured by its bandwidth and data
transfer rate.
BANDWIDTH: Bandwidth is the difference between the highest and lowest frequencies a transmission
media can carry. The unit of bandwidth is Hertz.
DATA TRANSFER RATES: Data transfer rate is the number of bits transmitted through a channel per
unit of time. Data transfer rate is measured in bits per second (bps). It is also measured in Kilobits per
second (Kbps), Megabits per second (Mbps) or Gigabits per second (Gbps).

IP ADDRESS: IP address or Internet Protocol address is a unique numeric address assigned to every
device connected to a network. It uniquely identifies every node connected to a local network or
internet. Example IP address: [Link]

SWITCHING TECHNIQUES
In large networks, there may be more than one paths for transmitting data from sender to receiver. The
process of selecting a path of data out of the available paths is called switching. There are two popular
switching techniques – circuit switching and packet switching.
1. Circuit Switching : In circuit switching, whenever a source end node wants to send a message to the
destination end node a physical link is first established between the source and the destination. Then
only the data transmission takes place. Example: telephone network
2. Packet Switching : In the packet switching technique, the whole message is split into small packets.
Now, these packets are transmitted one by one from sender to the receiver through the intermediary
switches in the network. The packets will take shortest path as possible.

TRANSMISSION MEDIA
• Transmission media are the channels used to carry data signals.
• They are broadly classified into
o Wired / Guided Media
Includes:
▪ Twisted pair cable
▪ Coaxial cable
▪ Fiber-optic cable
Features:
▪ High Speed

70 | P a g e
▪ Secure
▪ Used for comparatively shorter distances
o Wireless/Un-guided media
Includes:
▪ Radio waves
▪ Microwaves
▪ Infrared waves.
Features:
▪ The signal is broadcasted through air
▪ Less Secure
▪ Used for larger distances

Wired Communication Media:


• Twisted Pair Cable:
o Consists of two separately insulated copper wires twisted together to reduce
electromagnetic interference.
o It is commonly used for telephone lines and local area networks (LANs).
o Twisted Pair is of two types:
1. Unshielded Twisted Pair (UTP):
▪ UTP consists of two insulated copper wires twisted around one another.
▪ This type of cable has the ability to block interference and does not depend on
a physical shield for this purpose.
▪ It is used for telephonic applications.
Advantages of Unshielded Twisted Pair
• Least expensive
• Easy to install
• High-speed capacity
Disadvantages of Unshielded Twisted Pair
• Lower capacity and performance in comparison to STP
• Short distance transmission due to attenuation
2. Shielded Twisted Pair
▪ Shielded Twisted Pair (STP): Shielded Twisted Pair (STP) cable consists of a
special jacket (a copper braid covering or a foil shield) to block external
interference.
▪ It is used in fast data rate Ethernet and in voice and data channels of telephone
lines.
Advantages of Shielded Twisted Pair
• Better performance at a higher data rate in comparison to UTP
• Eliminates crosstalk
• Comparatively faster
Disadvantages of Shielded Twisted Pair
• Comparatively difficult to install and manufacture
• More expensive
• Bulky

71 | P a g e
• Coaxial Cable:
o Coaxial cable has an outer plastic covering containing an insulation layer made of PVC or
Teflon and 2 parallel conductors each having a separate insulated protection cover.
o The coaxial cable transmits information in two modes: Baseband mode(dedicated cable
bandwidth) and Broadband mode(cable bandwidth is split into separate ranges).
o Cable TVs and analog television networks widely use Coaxial cables.

Advantages of Coaxial Cable


• Coaxial cables have high bandwidth.
• It is easy to install.
• Coaxial cables are more reliable and durable.
• Less affected by noise or cross-talk or electromagnetic inference.
• Coaxial cables support multiple channels
Disadvantages of Coaxial Cable
• Coaxial cables are expensive.
• The coaxial cable must be grounded in order to prevent any crosstalk.
• As a Coaxial cable has multiple layers it is very bulky.
• There is a chance of breaking the coaxial cable and attaching a “t-joint” by hackers, this
compromises the security of the data.

• Optical Fiber Cable


o Optical Fibre Cable uses the concept of total internal reflection of light through a core made
up of glass.
o The core is surrounded by a less dense glass or plastic covering called the coating.
o It is used for the transmission of large volumes of data.
o The cable can be unidirectional or bidirectional.
o The WDM (Wavelength Division Multiplexer) supports two modes, namely unidirectional
and bidirectional mode.

72 | P a g e
Advantages of Optical Fibre Cable
• Increased capacity and bandwidth
• Lightweight
• Less signal attenuation
• Immunity to electromagnetic interference
• Resistance to corrosive materials
Disadvantages of Optical Fibre Cable
• Difficult to install and maintain
• High cost
Applications of Optical Fibre Cable
o Medical Purpose: Used in several types of medical instruments.
o Defence Purpose: Used in transmission of data in aerospace.
o For Communication: This is largely used in formation of internet cables.
o Industrial Purpose: Used for lighting purposes and safety measures in designing the interior
and exterior of automobiles.

Wireless Communication Media:


Radio Waves
Radio waves are easy to generate and can penetrate through buildings. The sending and receiving
antennas need not be aligned.
Frequency Range:3KHz - 1GHz. AM and FM radios and cordless phones use Radio waves for
transmission.
Types of Radio Waves:
• Short Wave: AM Radio
• VHF (Very High Frequency): FM Radio/TV
• UHF (Ultra High Frequency): TV
Radio Wave Components:
• Transmitter: Responsible for encoding the signal.
• Receiver: Responsible for decoding the signal.
Microwaves
It is a line-of-sight transmission i.e. the sending and receiving antennas need to be properly aligned
with each other. The distance covered by the signal is directly proportional to the height of the
antenna.
Frequency Range:1GHz - 300GHz.
Micro waves are majorly used for mobile phone communication and television distribution.
Advantages:
• Cheaper than using cables
• Freedom from land acquisition
• Ease of communication in difficult terrains
73 | P a g e
• Communication over oceans
Disadvantages:
• Insecure communication.
• Out of phase signal.
• Susceptible to weather conditions.
• Bandwidth is limited.
• High cost of design, implementation, and maintenance.
Infrared
Infrared waves are used for very short distance communication. They cannot penetrate through
obstacles. This prevents interference between systems.
Frequency Range:300GHz - 400THz.
It is used in TV remotes, wireless mouse, keyboard, printer, etc.

Difference Between Radio Waves, Micro Waves, and Infrared Waves


Basis Radiowave Microwave Infrared wave
Direction omni-directional unidirectional unidirectional
Penetration At low frequency, they At low frequency, they They cannot penetrate
can penetrate through can penetrate through through any solid object
solid objects and walls solid objects and walls. at and walls.
but high frequency high frequency, they
they bounce off the cannot penetrate.
obstacle.
Frequency range 3 KHz to 1GHz. 1 GHz to 300 GHz. 300 GHz to 400 GHz.
Security These offers poor These offers medium These offers high
security. security. security.
Attenuation is high. is variable. is low.
Government Some frequencies in Some frequencies in the There is no need of
License the radio-waves microwaves require government license to
require government government license to use use these waves.
license to use these. these.
Usage Cost moderate. high. very less.
Communication used in long distance Used in long distance not used in long distance
communication. communication. communication.

NETWORK DEVICES
Modem: Stands for "modulator-demodulator.", converts digital data from a computer into analog signals
for transmission over telephone lines or cable systems. Also it converts incoming analog signals back
into digital data for the computer. Used to connect to the internet via ISP (Internet Service Provider).

74 | P a g e
Ethernet Card: Also known as a network interface card (NIC)., enables a computer to connect to an
Ethernet network using Ethernet cables, Essential for wired network connections. Provides a physical
interface for networking using an RJ45 connector
RJ45 Connector: Registered Jack 45 connector, used to connect Ethernet cables to devices such as
computers, switches, and routers, Ensures a secure and reliable physical connection. Repeater:
Amplifies and retransmits signals in a network, extends the range of network signals, especially in large
or congested environments. Used to combat signal loss over long distances.
Hub: A basic networking device that connects multiple devices in a network, Broadcasts data to all
connected devices, causing network congestion and inefficiency, which can lead to collisions.
Switch: Intelligent device that connects devices in a network, Forwards data only to the device that
needs it, improving network performance and efficiency by reducing collisions.
Router: Manages traffic between different networks, such as your home network and the internet,
performs functions like assigning IP addresses, directing data, and providing security.
Gateway: Acts as an entry and exit point for data traveling between different networks or protocols
(e.g., LAN to WAN), translates data between different formats or protocols to ensure smooth
communication.
Wi-Fi Card: A wireless network adapter that allows a computer to connect to Wi-Fi networks.
Commonly found in laptops and mobile devices for wireless internet access

COMPUTER NETWORK TYPES


A computer network can be categorized by their size, complexity and geographical spread. A computer
network is mainly of four types:
• LAN (Local Area Network)
• PAN (Personal Area Network)
• MAN (Metropolitan Area Network)
• WAN (Wide Area Network)
PAN (Personal Area Network): Personal Area Network is a network of information technology devices
(laptop, mobile phones, media player and play stations) arranged within the range of an individual
person, typically within a range of 10 meters / covers an area of 30 feet.
LAN (Local Area Network): Local Area Network is a group of computers connected to each other in a
small area such as a building, office through a communication medium such as twisted pair, coaxial cable,
etc to share resources.
MAN (Metropolitan Area Network): A metropolitan area network is a network that covers a larger
geographic area that is spread over an area as big as a city by interconnecting different LAN to form a
larger network through a telephone exchange line.
WAN (Wide Area Network): A Wide Area Network is a network that extends over a large geographical
area such as states or countries through a telephone line, fiber optic cable or satellite links. The internet
is one of the biggest WAN in the world.

75 | P a g e
NETWORKING TOPOLOGIES
Bus
It uses a single cable, called a trunk or segment, along which all the computers of the network are
connected

Star
All computers are connected using cable segments to a central component called a switch. The signals
from the transmitting computer go through the switch to all the others.

Tree
Tree Topology is a topology which is having a tree structure in which all the computers are connected
like the branches which are connected with the tree.

NETWORK PROTOCOL: A protocol means the rules that are applicable for a network. Protocols
defines standardized formats for data packets, techniques for detecting and correcting errors etc.
TCP/IP (Transmission Control Protocol/ Internet Protocol)
• The IP protocol ensures that each computer or node connected to the Internet is assigned an IP
address, which is used to identify each node independently.
• TCP ensures that the message or data is broken into smaller chunks, called IP packets. Each of
these packets are routed (transmitted) through the Internet, along a path from one router to the
next, until it reaches the specified destination. TCP guarantees the delivery of packets on the

76 | P a g e
designated IP address. It is also responsible for ordering the packets so that they are delivered in
sequence.
FTP (File Transfer Protocol): It is a standard internet protocol provided by TCP/IP used for
transmitting the files from one host to another. It is mainly used for transferring the web page files from
their creator to the computer that acts as a server for other computers on the internet. It is also used for
downloading the files to computer from other servers.
SMTP (Simple Mail Transfer Protocol.): SMTP is a set of communication guidelines that allow
software to transmit an electronic mail over the internet is called Simple Mail Transfer Protocol.
Point-to-Point Protocol (PPP) is protocol that is used to directly connect one computer system to
another. Computers use PPP to communicate over the telephone network or the Internet.
Post Office Protocol version 3 (POP3) Protocol: (POP3) is a standard mail protocol used to receive
emails from a remote server to a local email client. POP3 allows you to download email messages on
your local computer and read them even when you are offline. J, and JVM
Telnet: Telnet is a program that allows a user to log on to a remote computer. Telnet provides a
connection to the remote computer in such a way that a local terminal appears to be at the remote side.
VoIP: VoIP stands for Voice over Internet Protocol. It is also referred to as IP telephony, internet
telephony, or internet calling.
Web Services: Web Services means the services provided by World Wide Web. The World Wide Web
provides services like chatting, emailing, video conferencing, e-learning, e-shopping, e-reservation, e-
groups and social networking.
World Wide Web (WWW): The World Wide Web commonly referred to as WWW, W3, or the Web is
an interconnected system of public webpages accessible through the Internet. It was invented by Tim
Berners-Lee in 1989. Major components of WWW are:
1. Web Server – It is a computer that stores website resources (web pages, images, videos, etc.).
2. Web Browser (Client) - A software application used to access the web resources.
3. Webpage - Hypertext documents formatted in Hypertext Mark-up Language (HTML) and
displayed in a web browser.
4. Website - A website is a collection of inter-linked web pages that is identified by a common
domain name (website name) and stored on a web server.
5. HTTP Protocol - It governs data (web page) transfer between a server and a client.
6. HTML- A mark-up language used to specify the structure of a webpage.
7. URL- Address used to identify documents and other web resources on the internet.
WEB ARCHITECTURE
Web is working based on a client-server architecture.

Client: It is a computer capable of requesting, receiving & displaying information in the form of web
pages or using a particular service from the service providers (Servers).

77 | P a g e
Servers: It is a remote computer which provides/transfers information to the client (in the form of web
pages) or access to particular services.
Difference between Internet and WWW
Internet World Wide Web(WWW)
Internet stands for Interconnected Networks WWW stands for World wide Web
Internet is a means of connecting a computer World Wide Web which is a collection of
to any other computer anywhere in the world. information which is accessed via the Internet.
Internet is infrastructure. WWW is service on top of that infrastructure.
Internet is primarily hardware-based WWW is more software-oriented as compared to
the Internet.
Internet uses TCP/IP protocol. WWW uses HTTP Protocol.
HTML (Hypertext Mark-up Language): It is a mark-up language that tells web browsers how to
structure the web pages you visit. It has a variety of tags and attributes for defining the layout and
structure of the web document. A HTML document has the extension .htm or .html. Hypertext is a text
which is linked to another html document via clickable links known as hyperlinks.
XML (eXtensible Mark-up Language): XML is a mark-up language like HTML but it is designed to
transport or store data. It does not have predefined tags but allows the programmer to use customized
tags. An XML document has the extension .xml.
HTML v/s XML
HTML XML
HTML stands for Hyper Text Mark-up Language XML stands for eXtensible Mark-up Language
HTML is a case insensitive. XML is case sensitive.
Predefined tags (commands). User defined tags (commands).
It is used for presentation of the Data. It is used for transportation of the Data.
Small errors can be ignored. Errors not allowed.
Closing tags are optional. Compulsory to use closing tags.
HTTP - Hyper Text Transfer Protocol: HTTP is used to transfer data across the web. HTTP specifies
how to transfer hypertext (linked web documents) between two computers. It allows users of the World
Wide Web to exchange information found on web pages.
Hypertext Transfer Protocol Secure (HTTPS) is an extension of the HTTP which is used for secure
communication over a computer network.
Domain Names: Every device connected to the Internet has a numeric IP address which is very difficult
to remember. Each computer server hosting a website or web resource is given a name known as
Domain Name corresponding to unique IP addresses. For example, IP addresses and domain names of
some websites are as follows:
Domain Name IP Address
[Link] [Link]
[Link] [Link]

78 | P a g e
The process of converting a hostname (such as [Link]) into the corresponding IP address
(such as [Link]) is called domain name resolution. Specialized DNS servers are used for domain
name resolution (DNS resolution).
URL-Uniform Resource Locator: Every web page that is displayed on the Internet has a specific
address associated with it, this address is known as the URL. The structure of a URL can be represented
as follows:
[Link]

Protocol Domain name foldername filename


The URL consists of four basic parts, namely, protocol, hostname, folder name and the filename.
Each one of these has a specific function.
1) The “protocol” indicates the type of Protocol (http/https/ftp etc.) being used. The protocol is
always followed by “://” and the host name.
2) The host name/domain name is the Internet address of a remote computer on which the files
reside.
3) The folder name indicates the name of the directory in which the files are located.
4) The filename specifies the name of the specific document to be displayed in the browser. The
filename itself consists of two pieces of information, the name of the file to be displayed and the
file extension, which specifies the file type (.htm for HTML file, .txt for a text file, .bmp for a bitmap
image, etc.)
The structure of a URL can be represented as follows:
Websites: A website is a collection of linked web pages (plus their associated resources) that share a
unique domain name.
Web page: Web page is an electronic document designed using HTM linked with hyperlinks.
Web Browser: Web browser is software program to navigate the web pages on the internet. E.g., Google
Chrome, Mozilla Firefox, Internet Explorer, Safari, Opera etc.
Cookie: A cookie is a small text file that stores information stored on your computer. Cookies often store
your settings for a website, such as your preferred language or location, pages visited.
Web Server: A web server is a computer or a group of computers hosting one or more websites. E.g.,
Apache, IIS etc.
Web Hosting: Web hosting is the process of uploading/saving the web content on a web server to make
it available on WWW.
Multiple Choice Questions
1 What are the three common types of computer networks?
a. ROM, MAN, LAN b. RAM, WAN, LAN
c. MAN, LAN, WAN d. None of the above
2 What is the Full form of LAN?
a. Local Area Network b. Local Access Network
c. Line And Networking d. Line-less Networking
3 Define what a LAN is?

79 | P a g e
a. Connected devices share the resources of a single processor or server within a small
geographic area
b. Normally find within a business and school
c. These are computers that share resources over a large area
d. None of the above
4 Mr. John is a small businessman who runs Hardware store. He has been experiencing problems
with his small accounting department, which he depends on to provide sales reports. Mr. John
wants to share information between his 7 computer stations and have one central printing
area. What type of network would you recommend to Mr. John?
a. MAN b. LAN c. WAN d. SAN
5 WAN covers a larger geographical area than MAN?
a. True b. False
6 A network that consists of both LANs and MANs is called a Wide area network?
a. True b. False
7 Arrange the Following Types of Networks according to their size, from largest to smallest?
a. LAN, WAN, MAN b. WAN, LAN, MAN
c. MAN, LAN, WAN d. WAN, MAN, LAN
8 You are a member of a club that deals with computer networks. The club has to take a project
to build a MAN. Where would this project likely take place?
a. A small building/organization b. University or college
c. Home d. None of the above
9 What is the full form of MAN ?
a. Magnetic Access Network b. Metropolitan Area Network
c. Multi-Area Network d. Multi-Access net
10 In your school there is a library, and you can use the internet to do research, this library will
most likely be a WAN network?
a. True b. False
11 Types of Networks are Categories by their Geographical Area cover?
a. True b. False
12 What’s a web browser?
a) A kind of spider
b) A computer that store www files
c) A person who likes to look at websites
d) A software program that allows you to access sites on the World Wide Web
13 A _____ is a document commonly written and is accessible through the internet or other network
using a browser?
a) Accounts b) Data c) Web page d) Search engine
14 Which of the following is used to read HTML code and to render Webpage?
a) Web Server b) Web Browser c) Web Matrix d) Weboni
15 Which of the following is a Web Browser?
a) MS-office b) Notepad c) Firefox d) Word 2007

80 | P a g e

You might also like