Study Material File Handling 2024-25
Study Material File Handling 2024-25
FILE:
A file is a stream of bytes stored on some permanent storage device like Hard Disk, Pen
Drive, CD/DVD etc. A file consists of data identified by a name with an extension stores on
some non-volatile storage/memory device.
E.g. Files can be any one of following types like Text file (.txt), data file (.dat, .csv), document
file (.docs), image file (.jpeg), audio file (.mp3), video file (.mp4), animation file (.gif),
executable file (.exe), font file(.ttf) etc.
DATA FILES:
Data files store data related to a specific application & usually does not contain instructions
or code to be executed. Some common file extensions used to store data are: .dat, .csv, .xml,
.vcf, .db, .sql etc
1. Text Files: A text file stores information in ASCII or UNICODE characters. As a result, text
files are faster and easier for a human to read and write than the binary files. In text files,
each line of text is terminated, (delimited) with a special character known as EOL (End of
Line) character and some internal translations take place when this EOL character is read or
written. Text files can be read or edit by any supporting text editor.
Examples of common text file formats: .txt, .doc, .rtf etc
2. Binary Files: A binary file contains information in almost same format in which the
information is held in memory i.e. in the binary form. In binary file, there is no delimiter for a
line and no need of translations. As a result, binary files are faster and easier for a program
to read and write than the text files. Any executable file is a binary file. The binary files do
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
not easy to understand by human. Examples of common binary file formats: .bin, .log, . pib
etc.
3. CSV Files: A comma-separated values (.csv extension) file is a delimited text file that
uses a comma to separate values. Each line of the file is a data record. Each record consists
of one or more fields, separated by commas. The use of the comma as a field separator is
the source of the name for this file format.
Default delimiter is comma (,). Other delimiters are tab (\t), colon (:), pipe (|), semicolon (;)
characters etc.
A CSV file typically stores tabular data (numbers and text) in plain text, in which each line will
have the same number of fields.
CSV files are normally created by programs that can handle large amounts of data. They are
a convenient way to export data from spreadsheets and databases as well as import or use it
in other programs.
CWD (Current Working Directory): The working directory or current working directory
(CWD) is a folder/directory in which your python program is operating/executing/stored.
E.g.
"C:\Users\VKV\AppData\Local\Local\Programs\Python\Python37-32\temp.py”
Or
“F:\relative2\relative1\relative\hello.py”
Here temp or hello are filenames and .py is python file extension and this temp.py or
hello.py are stored in latest/last directory/current folder Python37-32 or relative. This
Python37-32 or relative folders are called working directory or current working directory
(CWD) for temp.py file or hello.py respectively.
ABSOLUTE PATH: An absolute path is a path that contains the entire/full path to the file
or directory that we need to access. This path begins at the top-level directory of your
computer and ends with the file or directory that we wish to access. e.g.
"C:\Users\VKV\AppData\Local\Local\Programs\Python\Python37-32\temp.py”
Or
“F:\relative2\relative1\relative\hello.py”
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
The above path is starting from top-level directory i.e. C or E (Generally C drive is called root
directory in windows operating system and / (forward slash is called root directory in linux
operating system) and ending with the file temp.py or hello.py respectively for whom we
want to access. So, this complete path for temp.py or hello.py file is called absolute path.
Absolute path ensures the exact file location in our computer.
RELATIVE PATHS:
A relative path is the path that is relative to the current working directory in our computer.
The symbols one dot( .) and two consecutive dots ( .. ) can be used in relative paths in place
of current working directory and parent working directory respectively.
Let us understand by the following example:
From the above figure a path “F://relative/relative1” is a path where F is a top level
directory, relative2 is a child directory of F directory and parent directory for relative1
directory and relative1 is the child directory of relative2 directory. In relative2
directory/folder, test1.txt file is stored and in relative1 directory/folder, test.txt and
hellopath.py are stored. Here, we assume current directory in reference with python
program hellopath.py and are trying to read text files test.txt and test1.txt.
Now we can consider test.txt is stored in current directory(working directory) relative1 in
reference with hellopath.py and test1.txt is stored in parent directory relative2 in reference
with hellopath.py or relative1 directory.
Let us understand by python program:
“””Our python program hellopath.py and text file “test.txt” are stored in current working
directory relative1 “””
f=open(".\\test.txt","r")
print(f.read())
f.close()
OUTPUT:
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
“”” Our python program hellopath.py is stored in relative1 directory and “test1.txt” is
stored in parent directory relative2 “””
f=open("..\\test1.txt","r")
print(f.read())
f.close()
OUTPUT:
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
Note: The open() function returns an object of type _io.TextIOWrapper. The class
_io.TextIOWrapper provides functions and attributes, which helps us to read or write data to
and from the file e.g. read(), readline(), readlines(),write(), seek(), tell(), close() .
filename is an identifier, use for naming opening file name with file extension (i.e. .txt , .dat
). filename argument is passed in open function within double quotes or single quote (“
filename” ) or passed as a string literal as an argument. This filename can be passed as an
absolute path or as a relative path discussed above; Otherwise, we can pass filename
without path that means the file will open in current working directory of python program.
filemode is called File access Mode. The file access mode governs the type of operations
possible on the opened file. These are predefined in python and can be used/passed within
single or double quotes as an argument. The list of file access modes is:
TABLE: 1
Text File Binary File Description Remark
Mode Mode
“r” “rb” Read only File must be existed otherwise I/O error is raised
“w” “wb” Write only If the file does not exist, file is created by filename. If
the file is existed by the filename then it opens as a
new file that means previous data in this file get
truncated/removed/erased.
“a” “ab” Append Append means file opens by the filename in write
mode but we write data at last of the file where
previous existed data ends; this is called append.
If file does not exist then new file creates by provided
filename.
“r+” “r+b” or Read & File must exist otherwise error is raised. Both reading
“rb+” Write and writing operations can take place.
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
“w+” “w+b” or Write & File is created if does not exist. If file exists, file is
”wb+” Read truncated. Both writing and reading operations can
take place.
“a+” “a+b” or Append & File is created if does not exist. If file exists, file’s
“ab+” Read existing data is retained. New data is appended. Both
writing & reading operations can take place.
Note: If during opening file, filemode is not passed in open( ) function, then by default/
automatically the file opens in reading mode i.e. “r”.
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
string: It is an argument. We must pass data/content in single or double or triple quotes or
you can say that write function can write data in only string form.
# Program that open a text file and then write data/content on it.
f = open(“writeonfile.txt”, “w”)
f . write(“ Hello Students!!!! This is file handling magic”)
f.close( )
or
f = open(“writeonfile.txt”, “w”)
s = “ Hello Students!!!! This is file handling magic”
f . write( s )
f.close( )
or
with open("writeonfile.txt",”w”) as f:
f.write( “ Hello Students!!!! This is file handling magic” )
or
with open("writeonfile.txt",”w”) as f:
s=“ Hello Students!!!! This is file handling magic”
f.write( s )
Note:
i. We can also use open( ) function in the following way. With this way, we do not need to
close the file by close() function.
with open(“writeonfile.txt”,”w”) as f :
ii. After execution of above code(s) given in example 2.1, the output window does not show
any output, but we can see written data on writeonfile .txt file.
2.2 writelines( ) Functions: This function writes a list of string(s) to the text file.
Syntax:
fileobject . writelines(listofstrings)
Note:
i. It writes list of string(s) from the starting of text file or at the end of the previous existed
data on file depend upon provided writing file mode in open() function i.e. “w” or “a” .
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
ii. It returns None.
iii. After writing data through writelines() function, you should call flush( ) or close( )
function so that the contents of string transfer/write from buffer to text file otherwise you
get blank text file.
iv. We can use “ “, “\t” and “\n” with string(s) inside list, if we want to separate string(s) by
space, tabs and newline characters.
f = open(“writeonfile.txt”, “w”)
s = ([“It is my school\n”, ”I love my school\n”, ”My school name is KV, Lumding \n”])
f . writelines( s ) #multiple lines
f.close( )
or
with open("writeonfile.txt",”w”) as f:
f.writelines([ “ Hello Students!!!! This is file handling magic”] )
#single line
Note:
Buffer is a temporary storage area (could be a Register, Cache, RAM, etc ). The purpose of
most buffers is to act as a temporary holding area, enable the CPU/system to manipulate
data before transferring it to a permanent storage.
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
3. CLOSE OPERATION ON TEXT FILE:
After writing/appending/reading data to or from the text file, we should use close( )
function. Closing a file releases valuable system resources, which were assigned to a
fileobject. Python automatically flushes the files when we close the text file.
Syntax:
fileobject . close( )
e.g. f. close( )
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
“”” Program to read 10 characters in first attempt, then reads next 20 characters in second
attempt from text file “writeonfile.txt” “””
f = open(“writeonfile.txt”, “r”)
print(f.read(10))
print(f.read(20))
f.close( )
4.2 readline( ) function: This function is used to read single line at a time and can also read
specified number of characters of a line from the text file. Before reading text file by
readline( ) function, the file should be opened in the reading “r” mode. It returns a string or
a line.
Syntax:
fileobject . readline( ) or fileobject . readline(n )
Where n is an integer argument i.e. number of characters you wish to read of a line from
text file. If you do not pass any argument in readline( ) function then it reads entire line of
data. A line is considered till a newline character (EOL i.e. “\n” ) is encountered in the text
file.
e.g. f .readline( ) # It reads a line of data i.e. string from the text file
f.readline(10 ) # It reads 10 characters of a line i.e. string with 10
characters from the text file
#Program to read a line(first line) of data from text file “writeonfile.txt” .
f = open(“writeonfile.txt”, “r”)
s=f.readline( )
print(s)
f.close( )
# Program to read 10 characters of a line (first line) of data from the text file
“writeonfile.txt” .
f = open(“writeonfile.txt”, “r”)
s=f.readline(10)
print(s)
f.close( )
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
#Program to read entire data of text file line by line from text file “writeonfile.txt” .
f = open(“writeonfile.txt”, “r”)
str=” ”
while str :
s=f.readline( )
print( s ,end=””)
f.close( )
#Program to read entire data of text file line by line from text file “writeonfile.txt” .
f = open(“writeonfile.txt”, “r”)
for line in f: # file object can be iterated by for loop line by line
print(line)
f.close( )
4.3 readlines( ) function: This function is used to read all lines from the text file. Before
reading text file by readlines( ) function, the file should be opened in the reading “r” mode.
It returns a list of string line(s).
Syntax:
fileobject . readlines( )
e.g. f . readlines( )
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
i. tell( ) function:
It is used to return the current/present file pointer position/location in the file in terms of
byte number. It does not contain any argument.
Syntax:
fileobject . tell( )
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
means absolute file position. The value 1 is used when you want to use current file pointer
position as the reference position. The value 2 is used when we want to use ending of the
file as a reference position. By default whence argument is set to 0. seek( ) function returns
new absolute position.
Reference point i.e. whence at current position / end of file cannot be set in text mode
except when offset is equal to 0. seek() function with negative offset only works when file
is opened in binary mode.
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
Output:
======= RESTART: C:\Users\VIJENDRA KUMAR VYAS\Desktop\seekprogram.py ======
Hello friends, Python is amazing language
friends, Python is amazing language
41
36
guage
0
Hello friends, Python is amazing language
20
n is ama
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
#PROGRAM TO WRITE MULTIPLE LINES BY writelines( ) functions
f1=open("C:\\Users\\VIJENDRA KUMAR VYAS\\Desktop\\Test2.txt","w")
s=["Hello Students\n","Today we will discuss File Handling\n","Let's start our discussion"]
f1.writelines(s)
f1.close()
OUTPUT: A Text file created by name “Test2.txt”. Check your current directory or folder
where you saved your python program.
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
#Read a text file character by character
f=open(r"C:\Users\VIJENDRA KUMAR VYAS\Desktop\Test4.txt","r")
s=f.read()
for i in s:
print(i,end="")
f.close()
OUTPUT:
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
# Read a text file character by character
f=open(r"C:\Users\VIJENDRA KUMAR VYAS\Desktop\Test4.txt","r")
s=f.read()
l=len(s)
for i in range(l):
print(s[i], end="")
f.close()
OUTPUT:
#Read a text file character by character and count the type of characters
f=open("C:\\Users\\VIJENDRA KUMAR VYAS\\Desktop\\Test5.txt","r")
s=f.read()
print("Contents in the file:")
print(s)
counttc=0
countal=0
countdigit=0
countspace=0
countvowel=0
for i in s:
counttc+=1
if i.isalpha():
countal+=1
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
if i.isdigit():
countdigit+=1
if i==" ":
countspace+=1
i=i.lower()
if i=='a' or i=='e' or i=='i' or i=='o' or i=='u':
countvowel+=1
print( )
print("Total number of characters=", counttc)
print("Total number of alphabets=", countal)
print("Total number of digits=", countdigit)
print("Total number of spaces=", countspace)
print("Total number of vowels=", countvowel)
f.close()
OUTPUT:
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
print("Total number of words=",countwords)
f.close()
OUTPUT:
OUTPUT:
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
# Count number words start with "o"
f=open(r"C:\Users\VIJENDRA KUMAR VYAS\Desktop\Test7.txt","r")
s=f.readlines()
print(s)
countwords=0
for i in s:
line=i.split()
for j in line:
if j[0]=="o" or j[0]=="O":
countwords+=1
print("Total number of the words=",countwords)
f.close()
OUTPUT:
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
#Count the number of lines in a text file
f=open(r"C:\Users\VIJENDRA KUMAR VYAS\Desktop\Test7.txt","r")
s=f.readlines()
countlines=0
for i in s:
countlines+=1
print("Total number of lines=",countlines)
f.close()
OUTPUT:
#Count the number of lines starts with "the" word in the text file
f=open(r"C:\Users\VIJENDRA KUMAR VYAS\Desktop\Test7.txt","r")
s=f.readlines()
print(s)
countlines=0
for i in s:
#if i[0:3]=="the" or i[0:3]=="The":
if (i[0]=="t" or i[0]=="T") and i[1]=="h" and i[2]=="e":
countlines+=1
print("Total number of lines starts with 'the' word =",countlines)
f.close()
OUTPUT:
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
#Count the number of lines starts with "w" letter in the text file
f=open(r"C:\Users\VIJENDRA KUMAR VYAS\Desktop\Test7.text","r")
s=f.readlines()
print(s)
countlines=0
for i in s:
if (i[0]=="w" or i[0]=="W"):
countlines+=1
print("Total number of lines starts with 'w' letter =",countlines)
f.close()
OUTPUT:
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
#Count the number of lines having "overcome" word in the text file
f=open(r"C:\Users\VIJENDRA KUMAR VYAS\Desktop\Test7.txt","r")
s=f.readlines()
print(s)
countlines=0
for i in s:
line=i.split()
for j in line:
if j.lower()=="overcome" :
countlines+=1
break
print("Total number of lines having the word 'overcome' =",countlines)
f.close()
OUTPUT:
#PROGRAM TO WRITE AND READ MULTIPLE LINES TO AND FROM THE TEXT FILE
f1=open("C:\\Users\\VIJENDRA KUMAR VYAS\\Desktop\\Test1.txt","w")
f1.write("Hello Students\nToday we will discuss File Handling\nLet's start our discussion")
f1.close()
#Read the file
ff1=open(r"C:\Users\VIJENDRA KUMAR VYAS\Desktop\Test1.txt","r")
print(ff1.read())
ff1.close()
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
OUTPUT:
OUTPUT:
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
# Write a user defined function in Python named showInLines() which reads contents of a
text file named STORY.TXT and displays every sentence in a separate line. Assume that a
sentence ends with a full stop (.), a question mark (?), or an exclamation mark (!).
def showInLines():
with open("STORY.TXT",'r') as F:
S=F.read()
for W in S:
if W=="." or W=="?" or W=="!":
print(W)
elif W=="\n":
print(end="")
else:
print(W,end="")
F.close()
# Write a function, c_words() in Python that separately counts and displays the
number of uppercase and lowercase alphabets in a text file, Words.txt.
def c_words():
f=open("Words.txt","r")
Txt=f.read()
CLower=CUpper=0
for i in Txt:
if i.islower():
CLower+=1
elif i.isupper():
CUpper+=1
print(CLower, CUpper)
f.close()
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
CHECK YOUR KNOWLEDGE:
Q1. To open a file “c:\ss.txt” for appending data, we use
a. file = open(‘c:\\ss.txt’,’a’)
b. file = open(r‘c:\ss.txt’,’a’)
c. file = open(‘c:\\ss.txt’,’w’)
d. both a and b
Q2. To read the next line of the file from the file object infi, we use
a. infi.read(all)
b. infi.read()
c. infi.readline()
d. infi.readlines()
Q3. Which function is used to ensure that the data is written in the file immediately?
a. <filehandle>.write()
b. <filehandle>.writelines()
c. flush()
d. <filehandle>.close()
Q4. What is the datatype of the value returned by readlines() function?
a. Integer
b. String
c. List of strings
d. None of the above
Q5. What is the position of the cursor when the file is opened in append mode?
a. Start of file
b. End of file
c. At the 11th byte
d. Unknown
Q6. How to open a file such that close function is not needed to be called in order to close
the connection between file and python program?
a. Using open() method
b. Using read() method
c. Using with keyword
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
d. Using open with method
Q7. If a file is opened for writing
a. File must exist before opening
b. File will be created if does not exist
c. None of the above
d. Both a and b
Q8. If the cursor in the file is at the end of the file, then what will the read() function return?
a. None
b. False
c. Exception
d. Empty string
Q9. Which is the value of mode parameter to set the offset of the cursor from the end of the
file?
a. 0
b. 1
c. 2
d. None of the above
Q10. To open a file "c:marks.txt" for reading, we use
a. file_read = open("c:marks.txt", "r")
b. file_read = open("c:marks.txt", "r")
c. file_read = open(file = "c:marks.txt", "r")
d. file_read = open(file = "c:marks.txt", "r")
Q11: What is the use of tell() method in Python?
a. returns the current position of record pointer within the file
b. returns the end position of record pointer within the file
c. returns the current position of record pointer within the line
d. none of the above
Q12. Which of the following commands can be used to read "n" number of characters from
a file using the file object <File>?
a. File.read(n)
b. N = file.read()
c. File.readline(n)
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
d. File.readlines()
Q13. What is the correct syntax of open() function?
a. File = open(file_name[, access_mode][, buffering])
b. File object = open(file_name [, access_mode][,buffering])
c. File object = open(file_name)
d. None of the above
Q14. To read two characters from a file object "file_read"
a. file_read.read(2)
b. file_read(2)
c. file_read(read,2)
d. file_read.readlines(2)
Q15. The read() method returns____________.
a. str b. list
c. tuple d. None of these
Q16.
Assertion(A): To handle a file’s encoding format in Python, one must specify the encoding
type during the file opening process.
Reason(R) : Specifying the encoding type ensures that Python correctly interpretes the
contents of the file, preventing issues like UnicodeDecodeError when reading.
Choose the correct option:
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
Q17.
Assertion(A): Opening a file in ‘r+’ mode allows for both reading and writing operations on
the file.
Reason(R) : The ‘r+’ mode opens the file without truncating its contents, positioning the
cursor at the beginning of the file.
Choose the correct option:
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
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
c. A is True but R is False
d. A is false but R is True
Q18. What is the difference between opening mode ‘a’ and ‘w’?
Q19. What is the advantage of opening file using with keyword?
Q20. Aarti is new in python data-handling. Please help her to count the number of lines
which begins with ‘W’ or ‘w’ in poem.txt.
poem.txt
This is my Book.
Where is wish yours?
My Book is lying on the table.
Whom do we concern?
def count_poem():
file1=open(“……………………………”, “………………………………”) #Line 1
str1=file1.readlines()
count=0
for r1 in str1:
print(r1)
if …………………………………: #Line 2
…………………………. #Line 3
print(count)
file1.close()
………………………………………….. #Line 4
(a) # Line 1 : To open file POEM.txt in read mode
(b) # Line 2 : To check first character of every line is ‘W’ or ‘w’.
(c) # Line 3 : To increase the value of count by 1.
(d) # Line 4 : To call the function count_poem.
Q21. Write a method in python to read lines from a text file INDIA. TXT, to find and display
the Occurrence of the word "India".
Q22. Write a program that copies a text file "source.txt” onto "target.txt" barring the starting
with a "@" sign.
Q23. Write a program to read a text file line by line and display each word separated by a #.
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
Q24. SHRUTHI has to complete her file-based assignment by tonight. She has been given the
following text file (Education.txt):
Higher education improves quality of life. College graduates have longer life spans.
Education is birthright. Shruthi has also received the following incomplete code.
def fileFunction1 (____,____) #Fill_Line5
fi = ___(fname,___) #Fill_Line6
fi._______ #Fill_Line7
fi._______ #Fill_Line8
fi.close()
print("Done")
def fileFunction2(fname, N1, N2):
fi = open(fname)
print(fi.read(N1))
fi.readline()
print( fi.read(N2) )
a = fi.readlines ()
print(a)
N1 = 16 #Line1
N2 = 22 #Line2
String = "India strengthening" #Line3
fileFunction1( ____,____) #Fill_Line4
fileFunction2 ( 'Education.txt', N1, N2)
Help her to complete her assignment as per the following instructions.
a. Complete Fill_Line4 so that the function call to FileFunction1() passes two arguments:
First as the filename and the second as the string given in Line 3.
b. Complete Fill_Line5 so that the function header is as per its function call.
c. Complete Fill_Line6 so that the file is opened in a mode that will allow it to write the
string at the end of the file without deleting anything from the file.
d. Complete Fill_Line7 and FilI_Line8 so that the passed string is written on to the file,
followed by a newline character.
e. What will be the output produced by the complete code?
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
ANSWER KEYS:
Q1. d
Q2. c
Q3. c
Q4. c
Q5. b
Q6. c
Q7. a
Q8. d
Q9. c
Q10. (b) file_read = open("c:marks.txt", "r")
Q11. (a) returns the current position of record pointer within the file
Q12. (a) File.read(n)
Q13. (b) File object = open(file_name [, access_mode][,buffering])
Q14. a. file_read.read(2)
Q15. a. str
Q16. a. Both A and R are true and R is the correct explanation for A
Q17. a. Both A and R are true and R is the correct explanation for A
Q18. ‘w’ is used to write in file from the beginning. If file already exists then it will
overwrite the previous content.
‘a’ is also used to write in the file. If file already exists it will write after the previous
content.
Q19. With keyword reduces the overheads involved in the closing of the file after file
operation or handling the file closing after exception have occurred. When file is opened
using ‘with’ it will manage the closing of file at the end of the operations or after an
exception automatically.
Q20.
a) file1 = open("POEM.TXT","r")
(b) r1[0]=='W' or r1[0]=='w':
(c) count=count+1
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
(d) count_Poem()
Q21.
def display1():
count = 0
file = open( 'INDIA. TXT, 'r°)
for LINE in file:
Words= LINE. split()
for W in Words
if W== "India":
count= count +1
print (count)
file.close()
Q22.
def filter (oldfile, newfile):
fin = open(oldfile, "r")
fout open(newfile, "w")
while True:
text fin.readline()
if len(text) != 0:
if text[e] != "@":
fout.write(text)
fin.close()
fout.close()
filter("source.txt", "target.txt")
Q23.
myfile = open( "Answer.txt", "r")
line = " ”
while line:
line = myfile.readline() # one line read from file
# printing the line word by word using split()
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
for word in line.split():
print (word, end = '#*)
print()
#close the file
myfile.close()
Q24:
a. fileFunction1(" Education.txt', string)
b. def fileFunction1(fname, string):
c. fi open(fname, "a")
d. fi.write(string)
fi.write('\n')
e. Done
Higher education
college graduates have
[‘longer 1ife spans.\n', 'Education is birth right.\n', 'India strengthening\n']
6. Binary File:
A binary file contains information in almost same format in which the information is held in
memory i.e. in the binary form. In binary file, there is no delimiter for a line and no need of
translations. As a result, binary files are faster and easier for a program to read and write than
the text files. Any executable file is a binary file. The binary files do not easy to understand by
human. Examples of common binary file formats: .bin, .log, .pib, .blg, .bif etc.
Note: To deal binary file, one needs to import pickle module.
Pickle Module: Python pickle is used to serialize and deserialize a python object structure.
Any object on python can be pickled so that it can be saved on disk.
Pickling: Pickling is the process whereby a Python object hierarchy is converted into a byte
stream. It is also known as serialization
Unpickling: A byte stream is converted into object hierarchy.
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
Binary File Modes: File mode governs the type of operations read/write/append possible in
the opened file. It refers to how the file will be used once its opened.
Binary Description Remark
File
Mode
“rb” Read only File must be existed otherwise I/O error is raised
“wb” Write only If the file does not exist, file is created by filename. If the file is
existed by the filename then it opens as a new file that means
previous data in this file get truncated/removed/erased.
“ab” Append Append means file opens by the filename in write mode but we
write data at last of the file where previous existed data ends; this
is called append.
If file does not exist then new file creates by provided filename.
“r+b” or Read & Write File must exist otherwise error is raised. Both reading and writing
“rb+” operations can take place.
“w+b” or Write & Read File is created if does not exist. If file exists, file is truncated. Both
”wb+” writing and reading operations can take place.
“a+b” or Append & File is created if does not exist. If file exists, file’s existing data is
“ab+” Read retained. New data is appended. Both writing & reading
operations can take place.
The pickle module provides the following functions/methods to make the pickling process
more convenient:
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
i. dump()
ii. load()
To use the pickling methods in a program, we must import pickle module using import
keyword.
i. dump() : This method can write the pickled python object into a file object.
Syntax:
pickle.dump(dataobject, filehandle)
e.g. pickle.dump(listobj, f)
Where dataobject is the python object that is to be pickled(serialized) and filehandle is a file
object of the opened file.
ii. load( ) : This function reads the pickled representation of an object from the open file object
filehandle and return the reconstituted object hierarchy that was specified therein.
Syntax:
pickle.load(filehandle)
e.g.
f1=open("C:\\Users\\VIJENDRA KUMAR VYAS\\Desktop\\bfile1.bin","rb")
listobj=pickle.load(f1) # f1 is a filehandle, an object of opened file
SUPPORTING PROGRAMS:
#program to write a list data object to a binary file
import pickle
f=open("C:\\Users\\VIJENDRA KUMAR VYAS\\Desktop\\bfile1.bin","wb")
listobj=[1,2,3,4,5]
pickle.dump(listobj,f)
f.close()
f1=open("C:\\Users\\VIJENDRA KUMAR VYAS\\Desktop\\bfile1.bin","rb")
listobj=pickle.load(f1)
print(listobj)
f1.close()
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
#program to write a string data object to a binary file
import pickle
f=open("C:\\Users\\VIJENDRA KUMAR VYAS\\Desktop\\bfile1.bin","wb")
s="abc\ndef\n123"
pickle.dump(s,f)
f.close()
f1=open("C:\\Users\\VIJENDRA KUMAR VYAS\\Desktop\\bfile1.bin","rb")
listobj=pickle.load(f1)
print(listobj)
f1.close()
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
choice=input("Want to add more record(y/n):")
if(choice=='n'):
break
pickle.dump(list, file)
file.close()
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
print()
readrec=1
try:
with open("stufile.dat","rb") as f:
while True:
sdata=pickle.load(f)
print("Record Number : ",readrec)
print(sdata)
readrec=readrec+1
except EOFError:
pass
f.close()
OUTPUT:
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
print()
while True:
print("RECORD No.", recno)
rollno=int(input("\tStudent Roll number : "))
sname=input("\tStudent Name : ")
marks=int(input("\tStudent marks : "))
sdata=[rollno,sname,marks]
pickle.dump(sdata,f)
ans=input("Do you wish to enter more records (y/n)? ")
recno=recno+1
if ans.lower()=='n':
print("Record entry OVER ")
print()
break
# retrieving the size of file
print("Size of binary file (in bytes):",f.tell())
f.close()
# Reading the Student records from the file using load() module
print("Now Searching the Student records from the file")
print()
rno=int(input("Enter rollno whose record to be searched"))
try:
with open("stufile.dat","rb") as f:
while True:
sdata=pickle.load(f)
if sdata[0]==rno:
print("Record found\n")
print(sdata)
break
except EOFError:
pass
f.close()
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
OUTPUT:
# A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price]. Write a user
defined function CreateFile() to input data for a record and add to Book.dat binary file.
import pickle
f=open(“BOOK.DAT","wb")
ch='y'
while ch in "yY":
BookNo=int(input("Enter Book Number="))
BookName=input("Enter Book Name=")
Author=input("Enter Author Name=")
Price=float(input("Enter Price of the Book="))
Bookrecord=[BookNo,BookName,Author,Price]
pickle.dump(Bookrecord, f)
ch=input("Enter y or Y to add more book record, otherwise press any other character")
f.close()
OUTPUT:
Enter Book Number=1201
Enter Book Name=PHYSICS
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
Enter Author Name=NCERT
Enter Price of the Book=255
Enter y or Y to add more book record, otherwise press any other characterY
Enter Book Number=1202
Enter Book Name=COMPUTER SCIENCE
Enter Author Name=SUMITA ARORA
Enter Price of the Book=595
Enter y or Y to add more book record, otherwise press any other characterY
Enter Book Number=1203
Enter Book Name=CHEMISTRY
Enter Author Name=NCERT
Enter Price of the Book=260
Enter y or Y to add more book record, otherwise press any other characterN
def countrec():
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
f=open(" STUDENT.DAT","rb")
count=0
try:
while True:
srecord=pickle.load(f)
if srecord[2]>75:
count+=1
print(srecord)
except EOFError:
f.close()
print("Total number of students whose percentage are greater than 75%= ",count)
writerec()
countrec()
OUTPUT:
Enter Admission Number=1001
Enter Student Name=ASTITVA
Enter Student percentage=98
Enter y or Y to add more book record, otherwise press any other characterY
Enter Admission Number=1002
Enter Student Name=GAURAVI
Enter Student percentage=99
Enter y or Y to add more book record, otherwise press any other characterY
Enter Admission Number=1003
Enter Student Name=MAHIMA
Enter Student percentage=65
Enter y or Y to add more book record, otherwise press any other characterY
Enter Admission Number=1004
Enter Student Name=SAURYA
Enter Student percentage=71
Enter y or Y to add more book record, otherwise press any other characterY
Enter Admission Number=1005
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
Enter Student Name=AMIT
Enter Student percentage=86
Enter y or Y to add more book record, otherwise press any other characterN
(1001, 'ASTITVA', 98.0)
(1002, 'GAURAVI', 99.0)
(1005, 'AMIT', 86.0)
Total number of students whose percentage are greater than 75%= 3
# Write a program in python that would read contents from file “STUDENT1.DAT” and
creates a file named “STUDENT3.DAT” copying only those records from “STUDENT1.DAT”
where the student name is user entered name.
import pickle
f2=open("student1.dat","rb")
f3=open("student3.dat","wb")
uen=input("Enter complete student name for copying record=")
uen=uen.lower()
try :
s=" "
while s:
s=pickle.load(f2)
s1=s.lower()
if uen in s1:
pickle.dump(s,f3)
except EOFError :
pass
f2.close()
f3.close()
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
while s1:
s1=pickle.load(f4)
print(s1,end="")
except EOFError:
pass
f4.close()
OUTPUT:
Enter complete student name for copying record=abhay kumar
The data after writing record in student3.dat is:
1 Abhay Kumar Computer Science 86
3 Abhay Kumar Mathematics 76
# Write a program in python that writes the records on “STUDENT4.DAT” and update the
marks of the user entered student.
import pickle
f=open("student4.dat",'wb')
n=int(input("Enter how many Records you want to write:"))
for i in range(n):
roll=int(input("Enter roll number of student="))
name=input("Enter name of student=")
subject=input("Enter subject=")
marks=int(input("Enter marks out of 100 in this subject="))
record=[roll,name,subject,marks]
pickle.dump(record,f)
f.close()
f1=open("student4.dat",'rb+')
print("READING FILE")
sname=input("Name the student whose marks you want to update=")
new_marks=int(input("Enter new marks="))
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
f1.seek(0)
try :
while True:
rpos=f1.tell()
s=pickle.load(f1)
if s[1]==sname:
print("Old details of student=", s)
s[3]=new_marks
f1.seek(rpos)
pickle.dump(s,f1)
print("New updated details of this student=", s)
except EOFError :
pass
f1.close()
OUTPUT:
Enter how many Records you want to write:2
Enter roll number of student=1
Enter name of student=abhay
Enter subject=cs
Enter marks out of 100 in this subject=85
Enter roll number of student=2
Enter name of student=astitva
Enter subject=cs
Enter marks out of 100 in this subject=90
READING FILE
Name the student whose marks you want to update=abhay
Enter new marks=92
Old details of student= [1, 'abhay', 'cs', 85]
New updated details of this student= [1, 'abhay', 'cs', 92]
# Consider a binary file, items.dat, containing records stored in the given format:
{item_id: [item_name,amount]}
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
Write a function, Copy_new(), that copies all records whose amount is greater than
1000 from items.dat to new_items.dat.
import pickle
def Copy_new():
F2=open("new_items.dat","wb")
try:
F1=open("items.dat","rb")
Data1=pickle.load(F1)
Data2={}
for K,V in Data1.items():
if V[1]>1000:
Data2[K]=V
pickle.dump(Data2,F2)
F2.close()
except:
print("File not found!")
F1.close()
def disp_Detail():
try:
with open("EMP.DAT","rb") as F:
Data=pickle.load(F)
for D in Data:
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
if D[2]<25000:
print(D)
except:
print("File Not Found!!!")
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
a) f = open(‘sum_list’,’wb’); pickle. dump(L1,f)
b) f = open(‘sum_list’,’rb’); L1=pickle.dump(f)
c) f = open(‘sum_list’,’wb’); pickle.load(L1,f)
d) f = open(‘sum_list’,’rb’); L1=pickle.load(f)
16. Ranjani is working on the sports.dat file but she is confused about how to read data from
the binary file. Suggest a suitable line for her to fulfil her wish.
import pickle
def sports_read():
f1 = open("sports.dat","rb")
_________________
print(data)
f1.close()
sports_read()
17. Which of the following statement is incorrect in the context of binary files?
a. Information is stored in the same format in which the information is held in memory.
b. No character translation takes place
c. Every line ends with a new line character
d. pickle module is used for reading and writing
18. Which of the following statement opens a binary file record.bin in write mode and writes
data from a list L = [1,2,3,4] on the binary file?
a. with open('record.bin','wb') as myfile:
pickle.dump(L,myfile)
b. with open('record.bin','wb') as myfile:
pickle.dump(myfile,L)
c. with open('record.bin','wb+') as myfile:
pickle.dump(myfile,L)
d. with open('record.bin','ab') as myfile:
pickle.dump(myfile,L)
Q19: 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 the pickle module.
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
Reasoning (R): Binary files are just like normal text files and can be read using a text editor
like notepad.
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
Q20:
Consider a binary file “kvlmgdata.dat” which stores twenty records/data of list type, where
each object/record occupies 30 bytes each irrespective of number of characters. Astitva a
student of class XII, wants to display the last record but he is confused how to access this last
record. Please help him to fill the statement in the following code.
import pickle
f1=open(……………………………., "rb") #Statement 1
f1.seek(…………………, ………………….) #Statement 2
print(pickle.load(f1))
21. What is EOFError? How can we handle EOFError in python?
22. How text files and binary files are stored inside computer memory?
23. Name any two exceptions that occur while working with pickle module.
24. What is the difference between writer object’s writerow() and writerows() function?
25. Binary files are the best way to store program information. Discuss.
26.What are delimited text files? Give examples
27. What is a file object?
28. What is the difference between write() and writelines()?
29. What is pickle module? Why we use pickle module?
30. Write a code to show how a dictionary is stored as binary file.
31. What is pickle.dump()? What is pickle.load()?
32. A binary file “salary.DAT” has structure [employee id, employee name, salary]. Write a
function countrec() in Python that would read contents of the file “salary.DAT” and display
the details of those employee whose salary is above 20000.
33. A file sports.dat contains information in following format [event, participant].
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
Write a program that would read the contents from file and copy only those records from
sports.dat where the event name is “Athletics” in new file named Athletics.dat
34. A binary file “STUDENT.DAT” has structure [admission_number, Name, Percentage].
Write a function countrec() in Python that would read contents of the file “STUDENT.DAT”
and display the details of those students whose percentage is above 75. Also display number
of students scoring above 75%.
35. Amritya Seth is a programmer, who has recently been given a task to write a python code
to perform the following binary file operations with the help of two user defined
functions/modules:
a. AddStudents() to create a binary file called STUDENT.DAT containing student information –
roll number, name and marks (out of 100) of each student.
b. GetStudents() to display the name and percentage of those students who have a
percentage greater than 75. In case there is no student having percentage > 75 the function
displays an appropriate message. The function should also display the average percent.
He has succeeded in writing partial code and has missed out certain statements, so he has
left certain queries in comment lines. You as an expert of Python have to provide the missing
statements and other related queries based on the following code of Amritya
Answer any four questions (out of five) from the below mentioned questions.
import pickle
def AddStudents():
____________ #1 statement to open the binary file to write data
while True:
Rno = int(input("Rno :"))
Name = input("Name : ")
Percent = float(input("Percent :"))
L = [Rno, Name, Percent]
____________ #2 statement to write the list Linto the file
Choice = input("enter more (y/n): ")
if Choice in "nN":
break
F.close()
def GetStudents():
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
Total=0
Countrec=0
Countabove75=0
with open("STUDENT.DAT","rb") as F:
while True:
try:
____________ #3 statement to read from the file
Countrec+=1
Total+=R[2]
if R[2] > 75:
print(R[1], " has percent =",R[2])
Countabove75+=1
except:
break
if Countabove75==0:
print("There is no student who has percentage more than 75")
average=Total/Countrec print("average percent of class = ",average)
AddStudents()
GetStudents()
i. Which of the following commands is used to open the file “STUDENT.DAT” for writing only
in binary format? (marked as #1 in the Python code)
a. F= open("STUDENT.DAT",'wb')
b. F= open("STUDENT.DAT",'w')
c. F= open("STUDENT.DAT",'wb+')
d. F= open("STUDENT.DAT",'w+')
ii. Which of the following commands is used to write the list L into the binary file,
STUDENT.DAT ? (marked as #2 in the Python code)
a. pickle.write(L,f)
b. pickle.write(f, L)
c. pickle.dump(L,F)
d. f=pickle.dump(L)
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
iii. Which of the following commands is used to read each record from the binary file
STUDENT.DAT? (marked as #3 in the Python code)
a. R = pickle.load(F)
b. pickle.read(r,f)
c. r= pickle.read(f)
d. pickle.load(r,f)
iv. Which of the following statement(s) are correct regarding the file access modes?
a. ‘r+’ opens a file for both reading and writing. File object points to its beginning.
b. ‘w+’ opens a file for both writing and reading. Adds at the end of the existing file if it exists
and creates a new one if it does not exist.
c. ‘wb’ opens a file for reading and writing in binary format. Overwrites the file if it exists and
creates a new one if it does not exist.
d. ‘a’ opens a file for appending. The file pointer is at the start of the file if the file exists
v. Which of the following statements correctly explain the function of seek() method?
a. tells the current position within the file.
b. determines if you can move the file position or not.
c. indicates that the next read or write occurs from that position in a file.
d. moves the current file position to a given specified position
ANSWERS:
1. Binary files
2. Pickling
3. Unpickling
4. FileNotFoundError
5. r
6. Serialization.
7. Newline
8. c. Every line ends with a new line character
9. Files
10. Newline (\n)
11. Binary
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
12. pickle
13. dump()
14. load()
15. option d
16. data = f1.load(f).
17. c
18. with open('record.bin','wb') as myfile:
pickle.dump(L,myfile)
19. c. A is True but R is False
20. Statement 1: “kvlmgdata.dat”
Statement 2: 270, 0
OR
Statement 2: -30, 2
21 .EOFError is raised when one of the built-in functions input() or raw_input() hits an end-
of-file condition (EOF) without reading any data. We can overcome this issue by using try
and except keywords in Python, called Exception Handling.
22. A text file stores information in the form of a stream of ASCII or Unicode characters
based on the default state of programming languages. Binary file store information as
stream of bytes .
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
placed after each value. E.g.: CSV files – Comma Separated Files, TSV files – Tab separated
files
27. Python file object provides methods and attributes to access and manipulate files. Using
file objects, we can read or write any files. Whenever we open a file to perform any
operations on it, Python returns a file object.
28. The difference between write() and writeline() method is based on new line character.
write() method displays the output but do not provide a new line character.
writeline() method displays the output and also provides a new line character it the end
of the string, this would set a new line for the next
29. Pickle module provides us the ability to serialise and deserialize objects that is, it helps to
convert objects into bitstreams that can be stored in files and later utilised to recreate the
original objects.
For us, writing different kinds of objects into the binary file and later, reading the file's
content is really challenging. The fact that some of the objects may have changing lengths
makes this a tedious task. So we use the pickle module to solve this issue since it can handle
dictionaries, sets, lists, tuples, classes, and more. It can store lists, Tuples, dictionaries, sets,
classes etc.
30.
import pickle
F1 = open ("file.dat", "wb")
Icode = input ("Enter code : ")
quantity = int (input ("Quantity : "))
d = {Icode:quantity},
pickle.dump(d, F1)
F1.close()
31. dump() function is used to store the object data to the file.
dump( object, filehandle )
First argument is the object that we want to store. The second argument is the file object we
get by opening the desired file in write-binary (wb) mode.
load() function is used to retrieve pickled data.
mylist = pickle.load(filehandle)
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
The primary argument is the filehandle that you get by opening the file in read-binary (rb)
mode.
32.
def countrec():
num=0
fobj=open("data.dat","rb")
try:
print("Emp id\tEmp Name\tEmp Sal")
while True:
rec=pickle.load(fobj)
if rec[2]>20000:
print(rec[0],"\t\t",rec[1],"\t\t",rec[2])
except:
fobj.close()
countrec()
33.
import pickle
F1 = open ("sports.dat", "rb")
F2 = open ("athletics.dat", "wb")
sum = 0
while True:
try:
l = pickle.load(F1)
if (l[0].lower() == "athletics"):
print (l)
pickle.dump(l,F2)
except EOFError:
break
F1.close()
F2.close()
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
34.
import pickle
def countrec():
fobj=open("student.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[2]>75:
num = num + 1
print(rec[0],rec[1],rec[2])
except:
fobj.close()
return num
35.
i. a)
ii. c)
iii. a)
iv. a)
v. d)
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
CSV files are normally created by programs that can handle large amounts of data. They are
a convenient way to export data from spreadsheets and databases as well as import or use it
in other programs.
For example, we might export the results of a data mining program to a CSV file and then
import that into a spreadsheet to analyse the data, generate graphs for a presentation, or
prepare a report for publication.
To create a CSV file with a text editor i.e. Notepad, open a new file. Then enter the text data
separating each value with a comma and each row with a new line and save this file by any
name with the extension .csv.
Now you can open the file using Microsoft Excel or another spreadsheet program:
In the same way we can write/type data in Microsoft Excel or another spreadsheet program
and save it by a name with .csv extension and can open it by Notepad or another text editor
and here we get comma separated values.
Advantages of csv files:
• CSV is human readable and easy to edit manually.
• CSV is simple to implement and parse.
• CSV is processed by almost all existing applications.
• CSV is smaller in size
• CSV is considered to be standard format
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
• CSV is compact. For XML you start tag and end tag for each column in each row. In CSV you
write the column headers only once.
• CSV can handle large unstructured data generated by social media effectively
Note:
1. CR stands for the character 'Carriage Return' with Integer ASCII code - 13 and C++/Python
notation \r or '\r'.
2. LF stands for the character 'Line Feed' with Integer ASCII code - 10 and C++/Python
notation \n or '\n'.
3. In Windows platform the Enter Key / End of Line(EOL) / newline character is represented
by the character combination CRLF i.e. '\r\n' in python.
4. In Unix/Linux platforms the Enter Key /End of Line (EOL) / newline character is
represented by the character LF only i.e. '\n' in python.
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
5. In Macintosh platforms the Enter Key / End of Line (EOL) / newline character is
represented by the character CR only i.e. '\r' in python.
6. When opening a file for reading CSV file add the parameter, newline='EOL_character' to
process the End of Line correctly.
While opening a CSV file for reading on Windows platform, add the parameter,
newline='\r\n' in the open() method to avoid adding an extra blank line while
processing/displaying output on the screen
csv module:
csv module is used to storing, accessing and modifying data in CSV files through python
program. The csv module implements classes to read and write tabular data in CSV format. It
allows programmers to say, “write this data in the format preferred by Excel,” or “read data
from this file which was generated by Excel,” without knowing the precise details of the CSV
format used by Excel.
The csv module’s reader and writer objects read and write sequences.
Working with CSV files in Python:
While we could use the built-in open() function to work with CSV files in Python, there is a
dedicated csv module that makes working with CSV files much easier.
Before we can use the methods to the csv module, we need to import the module first
using: import csv
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
file =open(r"C:/Users/VIJENDRA KUMAR VYAS/Desktop/csvfile1.csv","w", newline= ’’)
Here the name of csv file is csvfile1. This file is opened in writing mode i.e. “w”. To prevent
additional space between lines, newline parameter is set to ‘ ’. We can ignore newline
parameter.
writerow( ) :
It writes the row parameter to the writer’s file object, formatted according to the current
dialect.
Syntax:
csvwriter.writerow(row)
i.e.
csvwrite.writeone([1, “Mr. Mohan”, “Doctor”])
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
It returns a reader object which will iterate over lines in the given csvfile. We can understand
that this function returns a reader object, which is used to iterate to find data rows in
comma separated values from the csv file.
Syntax:
csvreader= csv.reader(csvfile)
Where csvreader is an object which receives reader object and it is iterable. csvfile is the file
object related opened csv file.
Note:
1. Every row written in the file issues a newline character.
2. The above functions can have more arguments, here I discussed mandatory arguments
due to reduce complexity.
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
SUPPORTING PROGRAMS:
# Program to write rows one by one in csv file. Iterable object is List.
import csv
f=open(r"C:/Users/VIJENDRA KUMAR VYAS/Desktop/csvfile1.csv","w",newline='')
w = csv.writer(f)
print(w,type(w))
w.writerow(["SN", "NAME", "CLASS"])
w.writerow([1, "MANJEET", "XII B"])
w.writerow([2, "RISHIKKA", "XII B"])
w.writerow([3, "LOKESH", "XII B"])
f.close()
Output:
After execution a csv file created by csvfile1 and can be opened directly by excel or notepad.
# Program to write rows one by one in csv file. Iterable object is tuple.
import csv
f=open(r"C:/Users/VIJENDRA KUMAR VYAS/Desktop/csvfile2.csv","w")
“””In open function, newline argument =‘ ‘ is not passed. Therefore you can see space
between two rows ”””
w = csv.writer(f)
print(w,type(w))
w.writerow(("SN", "NAME", "CLASS"))
w.writerow((1, "MANJEET", "XII B"))
w.writerow((2, "RISHIKKA", "XII B"))
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
w.writerow((3, "LOKESH", "XII B"))
f.close()
Output:
After execution a csv file created by csvfile2 and can be opened directly by excel or notepad.
==== RESTART: C:\Users\VIJENDRA KUMAR VYAS\Desktop\csvfilewritetuple2.PY ====
<_csv.writer object at 0x03A7E540> <class '_csv.writer'>
# Program to write rows in single go by writerows() onto csv file. Iterable object is list.
import csv
f=open(r"C:/Users/VIJENDRA KUMAR VYAS/Desktop/csvfilewriterowslist.csv", "w",
newline='')
w = csv.writer(f)
nl=[[1,"Hari","Clerk"],[2,"Shyam","Manager"],[3,"Ram","CEO"]]
w.writerows(nl)
f.close()
Output:
After execution a csv file created by csvfilewriterowslist and can be opened directly by excel
or notepad.
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
# Program to write & read rows onto/from csv file. Iterable object is list.
import csv
# writing on csv file
f=open(r"C:/Users/VIJENDRA KUMAR VYAS/Desktop/csvfilewriterowslist.csv","w",newline='')
w = csv.writer(f)
nl=[[1,"Hari","Clerk"],[2,"Shyam","Manager"],[3,"Ram","CEO"]]
w.writerows(nl)
f.close()
# Reading from csv file
f1=open(r"C:/Users/VIJENDRA KUMAR
VYAS/Desktop/csvfilewriterowslist.csv","r",newline='')
r=csv.reader(f1)
for i in r:
print(i)
f1.close()
Output:
=== RESTART: C:\Users\VIJENDRA KUMAR VYAS\Desktop\csvfilewriterowslist.py ===
['1', 'Hari', 'Clerk']
['2', 'Shyam', 'Manager']
['3', 'Ram', 'CEO']
# Program to write & read rows onto/from csv file. Iterable object is dictionary.
import csv
f=open(r"C:/Users/VIJENDRA KUMAR VYAS/Desktop/csvfile3.csv","w",newline='')
w = csv.writer(f)
d={1:"NER",2:"JLA",3:"IVRI"}
for key,value in d.items():
w.writerow([key,value])
f.close()
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
dd=csv.reader(f1)
rd={}
for key in dd:
rd.update({int(key[0]):key[1]})
print(rd)
f1.close()
Output:
===== RESTART: C:\Users\VIJENDRA KUMAR VYAS\Desktop\csvfilewritedict3.py =====
{1: 'NER', 2: 'JLA', 3: 'IVRI'}
import csv
def Add_Device():
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
F=open("Peripheral.csv","a",newline='')
W=csv.writer(F)
P_id=int(input("Enter the Peripheral ID"))
P_name=input("Enter Peripheral Name")
Price=int(input("Enter Price"))
L=[P_id,P_name,Price]
W.writerow(L)
F.close()
def Count_Device():
F=open("Peripheral.csv","r")
L=list(csv.reader(F))
Count=0
for D in L:
if int(D[2])<1000:
Count+=1
print(Count)
F.close()
# Vedansh is a Python programmer working in a school. For the Annual Sports Event, he
has created a csv file named Result.csv, to store the results of students in different sports
events. The structure of Result.csv is : [St_Id, St_Name, Game_Name, Result]
Where
St_Id is Student ID (integer)
ST_name is Student Name (string)
Game_Name is name of game in which student is participating(string)
Result is result of the game whose value can be either 'Won', 'Lost' or 'Tie'
For efficiently maintaining data of the event, Vedansh wants to write the following user
defined functions:
Accept() – to accept a record from the user and add it to the file Result.csv. The column
headings should also be added on top of the csv file.
wonCount() – to count the number of students who have won any event.
As a Python expert, help him complete the task.
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
def Accept():
sid= int(input(“Enter Student Id:”))
sname= input(“Enter Student Name:”)
game= input(“Enter name of the game:”)
res=input(“Enter result:”)
heading= [“Student ID”, “Student Name”, “Game Name”, “Result”]
data=[sid, sname, game, res]
f=open(“Result.csv”, “a”, newline=””)
csvwriter=csv.writer(f)
csvwriter.writerow(heading)
csvwriter.writerow(data)
f.close()
def wonCount():
f=open(“Result.csv”, “r”)
csvreader=csv.reader(f, delimiter=”,”)
head=list(csvreader)
print(head[0])
for i in head:
if i[3]==”Won” :
print(i)
f.close()
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
3. A ________ parameter is used to quote all fields of csv files.
4. Read following statement about features of CSV file and select which statement is TRUE?
Statement1: Only database can support import/export to CSV format Statement2: CSV file
can be created and edited using any text editor Statement3: All the columns of CSV file can
be separated by comma only
a. Statement 1 and statement 2
b. Statement 2 and statement 3
c. Statement 2
d. Statement 3
5. Which of the following file types can be opened with notepad as well as ms excel?
a. Text Files
b. Binary Files
c. CSV Files
d. None of thes
6. Assertion (A): csv is a file format for data storage which looks like a text file.
Rasoning (R): The information is organised with one record on each line and each field is
separated by comma.
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
7. Write a program to copy the data from “data.csv” to “temp.csv”.
8. When is a CSV file? When do we use CSV?
9. Write a Python program to modify an existing file.
10. Write a Python program to read each row from a given csv file and print a list of strings
department_id, department_name, manager_id, location_id
10,Administration,200,1700
20,Marketing,201,1800
30,Purchasing,114,1700
40,Human Resources,203,2400
50,Shipping,121,1500
60,IT,103,1400
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
70,Public Relations,204,2700
80,Sales,145,2500
90,Executive,100,1700
11. Radha Shah is a programmer, who has recently been given a task to write a python code
to perform the following CSV file operations with the help of two user defined functions/
modules:
a. CSVOpen() : to create a CSV file called BOOKS.CSV in append mode containing
information of books – Title, Author and Price.
b. CSVRead() : to display the records from the CSV file called BOOKS.CSV where the
field title starts with 'R'.
She has succeeded in writing partial code and has missed out certain statements, so she has
left certain queries in comment lines.
import csv
def CSVOpen():
with open('books.csv','______',newline='') as csvf: #Statement-1
cw=______ #Statement-2
______ #Statement-3
cw.writerow(['Rapunzel','Jack',300])
cw.writerow(['Barbie','Doll',900])
cw.writerow(['Johnny','Jane',280])
def CSVRead():
try:
with open('books.csv','r') as csvf:
cr=______ #Statement-4
for r in cr:
if ______: #Statement-5
print(r)
except:
print('File Not Found')
CSVOpen()
CSVRead()
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
You as an expert of Python have to provide the missing statements and other related queries
based on the following code of Radha.
Answer the following questions:
i. Choose the appropriate mode in which the file is to be opened in append mode
(Statement 1)
a. w+
b. ab
c. r+
d. a
ii. Which statement will be used to create a csv writer object in Statement 2.
a. csv.writer(csvf)
b. csv.writer(csvf)
c. csvf.writer()
d. cs.writer(csvf)
iii. Choose the correct option for Statement 3 to write the names of the column headings in
the CSV file, BOOKS.CSV.
a. cw.writerow('Title','Author','Price')
b. cw.writerow(['Title','Author','Price'])
c. cw.writerows('Title','Author','Price')
d. cw.writerows(['Title','Author','Price'])
iv. Which statement will be used to read a csv file in Statement 4.
a. cs.read(csvf)
b. csv.reader(csvf)
c. csvf.read()
d. csvf.reader(cs)
v. Fill in the appropriate statement to check the field Title starting with ‘R’ for Statement 5 in
the above program.
a. r[0][0]=='R'
b. r[1][0]=='R'
c. r[0][1]=='R'
d. d) r[1][1]=='R'
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
Answers:
1. (D) Carriage Return and Line Feed
2. True
3. Quoting
4. c. Statement 2
5. CSV Files
6. a. Both A and R are true and R is the correct explanation for A
7.
import csv
f=open("data.csv","r")
f1=open("temp.csv",'w')
d=csv.reader(f)
d1=csv.writer(f1)
for i in d:
d1.writerow(i)
f.close( )
f1.close( )
8. A CSV (Comma Separated Values) file is a form of plain text document which uses a
particular format to organize tabular information. CSV file format is a bounded text
document that uses a comma to distinguish the values. Every row in the document is a data
log. Each log is composed of one or more fields, divided by commas. It is the most popular
file format for importing and exporting spreadsheets and databases.
9.
import csv
row = [‘3’, ‘Meena’, ’Bangalore’]
with open(‘student.csv’, r’) as readFile:
reader = csv.reader(readFile)
lines = list(reader) # list()- to store each row of data as a list
lines [3] = row
with open( student.csv’, ‘w’) as writeFile:
# returns the writer object which converts the user data with delimiter
writer = csv.writer(writeFile) #writerows()method writes multiple rows to a csv file
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
writer.writerows(lines)
10.
import csv
with open('departments.csv', newline='') as csvfile:
data = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in data:
print(', '.join(row))
11.
i. d. a
ii. b. csv.writer(csvf)
iii. b. cw.writerow(['Title','Author','Price'])
iv. b. csv.reader(csvf)
v. a. r[0][0]=='R'
Data Structure:
A data structure is a named group of data of different data types which is stored in a specific
way and can be processed as a single unit. It has well-defined operations, behaviour and
properties.
A data structure is a way of store, organize, or manage data in efficient and productive
manner.
Different data structures:
The data structures can be classified into following two types:
Simple Data Structures: These data structures are normally built from primitive data types
like integers, reals, characters, Boolean.
Following data structures can be termed as simple data structures.
Array or linear lists
Compound data structures: Simple data structures can be combined in various ways to form
more complex structures called compound data structures.
Compound data structures are classified into following two types:
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
(i) Linear data structures: These data structures are single level data structures. A data
structure said to be linear if its elements form a sequence.
Example: - Stack, queue, and linked list.
(ii) Non-linear data structures: These are multilevel data structures.
Example: - Trees, Graphs.
STACK:
The python data structure stack is a linear data structure. Stack follows LIFO (Last in first out)
principle using which an element inserted in the last will be the first one to be out.
You can also say that a stack is a restricted list in which insertion and deletion can occur only
from a single end i.e. top/last.
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
v. Stack is implemented in python through a list data type.
vi. When a stack is empty and we try to pop/delete an element from stack, it will raise an
error that is known as underflow.
vii. If you try to push more and more elements while the size of a stack is fixed and cannot
grow further or there is no memory left to accommodate new item, it will raise an error that
is known as overflow.
Some Examples of stack:
Example:
1. Books in the shelf
2. Stack of coins
3. Pile of chairs
4. Bangles on woman’s wrist
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
ii. To add/push an element in a stack:
stack.append(element)
iii. To delete/pop an element from a stack:
stack.pop( )
iv. To check whether a stack is empty (condition to check an underflow state):
if stack == [ ]:
print(“ Stack is empty or an underflow state”)
OR
if len(stack) == 0:
print(“ Stack is empty or an underflow state”)
v. To display the stack elements:
print(stack)
vi. To display the stack topmost elements:
print(stack[len(stack)-1])
vi. To display the stack elements in reverse order:
print(stack[ : : -1])
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
elif choice==3:
if len(stack)==0:
print("There is no element in the Stack, Excuse Me..")
else:
print("The elements in the stack=")
for i in range(-1,-len(stack)-1,-1):
print(stack[i])
elif choice==4:
exit()
print("Enter your choice: 1 for Push, 2 for Pop, 3 for Display, 4 for exit")
choice=int(input("Enter you choice"))
OUTPUT:
Enter your choice: 1 for Push, 2 for Pop, 3 for Display, 4 for exit
Enter you choice1
Enter the element you want to push=10
Enter your choice: 1 for Push, 2 for Pop, 3 for Display, 4 for exit
Enter you choice1
Enter the element you want to push=20
Enter your choice: 1 for Push, 2 for Pop, 3 for Display, 4 for exit
Enter you choice1
Enter the element you want to push=30
Enter your choice: 1 for Push, 2 for Pop, 3 for Display, 4 for exit
Enter you choice3
The elements in the stack=
30
20
10
Enter your choice: 1 for Push, 2 for Pop, 3 for Display, 4 for exit
Enter you choice2
Deleted item= 30
Enter your choice: 1 for Push, 2 for Pop, 3 for Display, 4 for exit
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
Enter you choice3
# Julie has created a dictionary containing names and marks as key value pairs of 6 students.
Write a program, with separate user defined functions to perform the following operations:
● Push the keys (name of the student) of the dictionary into a stack, where the
corresponding value (marks) is greater than 75.
● Pop and display the content of the stack.
For example: If the sample content of the dictionary is as follows:
R={"OM":76, "JAI":45, "BOB":89, "ALI":65, "ANU":90, "TOM":82}
The output from the program should be: TOM ANU BOB OM
sd={}
stack=[]
def addindict():
for i in range(6):
name=input("Enter name of student=")
marks=int(input("Enter marks out of 100="))
sd[name]=marks
print("Dictionary Elements are=")
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
print(sd)
def pushkeys():
for key in sd:
if sd[key]>75:
stack.append(key)
def popkeys():
if stack==[]:
print("Underflow, can't delete keys")
else:
delkey=stack.pop()
print("Deleted key =",delkey)
addindict()
pushkeys()
print("Stack elements are=")
for i in stack[::-1]:
print(i)
popkeys()
print("Stack elements are=")
for i in stack[::-1]:
print(i)
OUTPUT:
Enter name of student=MAHESH
Enter marks out of 100=86
Enter name of student=SURESH
Enter marks out of 100=65
Enter name of student=MAHIMA
Enter marks out of 100=96
Enter name of student=RAJA
Enter marks out of 100=79
Enter name of student=MANISH
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
Enter marks out of 100=91
Enter name of student=RAJU
Enter marks out of 100=74
Dictionary Elements are=
{'MAHESH': 86, 'SURESH': 65, 'MAHIMA': 96, 'RAJA': 79, 'MANISH': 91, 'RAJU': 74}
Stack elements are=
MANISH
RAJA
MAHIMA
MAHESH
Deleted key = MANISH
Stack elements are=
RAJA
MAHIMA
MAHESH
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
c) Pop <stack>.pop() d) Plus <stack>plus()
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
4. c) Array
5. a) peak operation
6. d) Plus <stack>plus()
7. c) A is True but R is False
2.
def AddPlayer(player):
pn=input("enter player name:")
player.append(pn)
def DeletePlayer(player):
if player==[]:
print("No player found")
else:
return player.pop()
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25
Answer the following questions (5 marks)
1.
def push(stk,item):
stk.append(item)
def Pop(stk):
if stk==[]:
return None
else:
return stk.pop()
stk=[]
d={"Ramesh":58, "Umesh":78, "Vishal":90, "Khushi":60, "Ishika":95}
for i in d:
if d[i]>70:
push(stk,i)
while True:
if stk!=[]:
print(Pop(stk),end=" ")
else:
break
NOTES COMPILED & PREPARED BY: V. K. VYAS, PGT(CS) KV LUMDING, SESSION: 2024-25