0% found this document useful (0 votes)
73 views26 pages

File Handling in Python

Uploaded by

luthrakanav
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)
73 views26 pages

File Handling in Python

Uploaded by

luthrakanav
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
You are on page 1/ 26

FILE HANDLING IN PYTHON

File : A file is a named location on a secondary storage media where data are
permanently stored for later access. Computers store every file as a collection
of 0s and 1s i.e., in binary form. Therefore, every file is basically just a series of
bytes stored one after the other.

TYPES OF FILES :

There are mainly two types of data files — text file and binary file.

Text File Binary File


A text file consists of human readable Binary files are made up of non-
characters, which can be opened by human readable characters and
any text editor. symbols, which require specific
programs to access its contents.
Each line of a text file is terminated by There is no EOL character.
a special character, called the End of
Line (EOL). For example, the default
EOL character in Python is the
newline (\n).
Bytes stored in text file represent the Bytes stored in binary file represent
ASCII values of the characters. the actual content such as image,
audio, video, compressed versions of
other files, executable files, etc.

Drawbacks of Binary file :

1. Binary files are stored in a computer in a sequence of bytes. Even a


single bit change can corrupt the file and make it unreadable to the
supporting application.
2. It is difficult to remove any error which may occur in the binary file as
the stored contents are not human readable.

Note :

1. Trying to open a binary file using a text editor will show some garbage
values.
2. When a text editor or a program interpreter encounters the ASCII
equivalent of the EOL character, it displays the remaining file contents
starting from a new line.
3. Contents in a text file are usually separated by whitespace, but comma
(,) and tab (\t) are also commonly used to separate values in a text file.

Operation on Files:

We broadly access files either to write or read data from it. But operations on
files include creating and opening a file, writing data in a file, traversing a file,
reading data from a file and so on. Python has the io module that contains
different functions for handling files.

1. Opening a File :
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)

open() function returns a file object called file handle which is stored in
the variable file_object.
We can use this variable to transfer data to and from the file (read and
write) by calling the functions defined in the Python’s io module.

Attributes of File Handle:

The file Handle has certain attributes that tells us basic information
about the file. Some of them are as follow :
• <file.closed> returns true if the file is closed and false otherwise.
• <file.mode> returns the access mode in which the file was opened.
• <file.name> returns the name of the file.

 The file_name should be the name of the file that has to be opened. If
the file is not in the current working directory, then we need to specify
the complete path of the file along with its name.
 The access_mode is an optional argument that represents the mode
in which the file has to be accessed by the program. It is also referred
to as processing mode. Mode means the operation for which the file
has to be opened like <r> for reading, <w> for writing, <+> for both
reading and writing, <a> for appending at the end of an existing file.

NOTE :

1. The default access_mode is the read mode.


2. We can specify whether the file will be handled as binary (<b>) or
text mode. By default, files are opened in text mode that means
strings can be read or written.
3. Files containing non-textual data are opened in binary mode that
means read/write are performed in terms of bytes.
4. The position of the file object , when the file is opened in a
particular mode is called File Offset Position.

File Description File Offset Position


Mode
<r> Opens the file in read-only mode. Beginning of the file
<rb> Opens the file in binary and read- Beginning of the file
only mode.
<r+> or Opens the file in both read and Beginning of the file
<+r> write mode.
<w> Opens the file in write mode. If the Beginning of the file
file already 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 Beginning of the file
or binary mode. If the file already
<+wb> 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 End of the file
the file doesn’t exist, then a new
file will be created.
<a+> Opens the file in append and read End of the file
mode. If the file doesn’t exist, then
it will create a new file.

Example :

File1 =open(“ABC.txt”, “a+”)

2. Closing a 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()
file_object is the object that was returned while opening the file.

Note :
 Python makes sure that any unwritten or unsaved data is flushed
off (written) to the file before it is closed. Hence, it is always
advised to close the file once our work is done.
 If the file object is re-assigned to some other file, the previous file
is automatically closed.

Opening a file using with clause :

In Python, we can also open a file using ‘with’ clause.


The syntax of with clause is:
with open (file_name, access_mode) as file_ object:
Example :
with open( “ABC.txt”, “r”) as file1 :
Note :

1. The advantage of using with clause is that any file that is opened using
this clause is closed automatically, once the control comes outside the
with clause.
2. In case the user forgets to close the file explicitly or if an exception
occurs, the file is closed automatically.
3. Also, it provides a simpler syntax.
with open(“myfile.txt”,”r+”) as myObject:
content = myObject.read()

3. WRITING TO A TEXT FILE :


For writing to a file, we first need to 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

The write() method :

Syntax : file_object.write(<String>)

 write() method takes a string as an argument and writes it to the text file.
 It returns the number of characters being written on single execution of
the write() method.
 Also, we need to add a newline character (\n) at the end of every
sentence to mark the end of line.
 Consider the following piece of code:

>>> myobject=open("myfile.txt",'w')
>>> myobject.write("Hey I have started #using files in Python\n")
45
>>> myobject.close()
On execution, write() returns the number of characters written on to the file.
Hence, 41, which is the length of the string passed as an argument, is
displayed.

Note: ‘\n’ is treated as a single character If numeric data are to be written to a


text file, the data need to be converted into string before writing to the file.

For example:

>>>myobject=open("myfile.txt",'w')
>>> marks=58 #number 58 is converted to a string using #str()
>>> myobject.write(str(marks))
2
>>>myobject.close()

The write() actually writes data onto a buffer. When the close() method is
executed, the contents from this buffer are moved to the file located on the
permanent storage.

The writelines() method :

Syntax : file_object.writelines(<List of Strings>)

 Writelines() method is used to write multiple strings to a file.


 We need to pass an iterable object like lists, tuple, etc. containing strings
to the writelines() method.
 Unlike write(), the writelines() method does not return the number of
characters written in the file. The following code explains the use of
writelines().
>>> myobject=open("myfile.txt",'w')
>>> lines = ["Hello everyone\n", "Writing
#multiline strings\n", "This is the
#third line"]
>>> myobject.writelines(lines)
>>>myobject.close()

On opening myfile.txt, using notepad, its content will appear as shown :


Contents of myfile.txt
4. 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:

(i) The read() method :This method is used to read a specified


number of bytes of data from a data file. The syntax of read()
method is:
file_object.read(n)
Example :
>>>myobject=open("myfile.txt",'r')
>>> myobject.read(10) 'Hello ever'
>>> myobject.close()

If no argument or a negative number is specified in read(), the


entire file content is read.
For example,
>>> myobject=open("myfile.txt",'r')
>>> print(myobject.read())
Hello everyone
Writing multiline strings
This is the third line
>>> myobject.close()
(ii) The readline([n]) method : This method reads one complete line
from a file where each line terminates with a newline (\n)
character. It can also be used to read a specified number (n) of
bytes of data from a file but maximum up to the newline character
(\n).
In the following example, the second statement reads the first ten
characters of the first line of the text file and displays them on the
screen.
>>> myobject=open("myfile.txt",'r')
>>> myobject.readline(10)
'Hello ever'
>>> myobject.close()

If no argument or a negative number is specified, it reads a


complete line and returns string.

>>>myobject=open("myfile.txt",'r')
>>> print (myobject.readline())
'Hello everyone\n'
To read the entire file line by line using the readline(), we can use a
loop. This process is known as looping/ iterating over a file object.
It returns an empty string when EOF is reached.

(iii) The readlines() method The method reads all the lines and
returns the lines along with newline as a list of strings.
The following example uses readlines() to read data from the text
file myfile.txt.

>>> myobject=open("myfile.txt", 'r')


>>> print(myobject.readlines())
['Hello everyone\n', 'Writing multiline strings\n', 'This is the third
line']
>>> myobject.close()

As shown in the above output, when we read a file using


readlines() function, lines in the file become members of a list,
where each list element ends with a newline character (‘\n’).
In case we want to display each word of a line separately as an
element of a list, then we can use split() function.

The following code demonstrates the use of split() function.


>>> myobject=open("myfile.txt",'r')
>>> d=myobject.readlines() Act
>>> for line in d:
words=line.split()
print(words)
['Hello', 'everyone']
['Writing', 'multiline', 'strings']
['This', 'is', 'the', 'third', 'line']
In the output, each string is returned as elements of a list.
However, if splitlines() is used instead of split(), then each line is
returned as element of a list, as shown in the output below:
>>> for line in d:
words=line.splitlines()
print(words)
['Hello everyone']
['Writing multiline strings']
['This is the third line'] ivi.4

Q. write a program that accepts a string from the user and writes it to a text
file. Thereafter, the same program reads the text file and displays it on the
screen.
Ans.

def writedata():

fobject=open("testfile.txt","w") # creating a data file


sentence=input("Enter the contents to be written in the file: ")
fobject.write(sentence) # Writing data to the file
fobject.close() # Closing a file
def displaydata():
fobject=open("testfile.txt","r)
for str in fobject: #looping over the file object to read the file
print(str)
fobject.close()
#-------------------------------------------------------
writedata()
print("Now reading the contents of the file: ")
displaydata()

Q. Define a function create_text() to create a text file ‘para.txt’.


Ans. # creating a text file using write() method
def create_text() :
file1 = open(“para.txt”, “a”)
while True :
S = input(“Enter the text : “)
file1.write(S)
file1.write(‘\n’)
ch = input”Wish to write more text(Y/N) : “)
if ch in (‘N’, ‘n’) :
break
file.close()

Ans. # creating a text file using writelines() method


def create_text() :
file1 = open(“para.txt”, “a”)
Lst = [] # empty list
while True :
S = input(“Enter the text : “)
S1 = S + “\n”
Lst.append(S1)
ch = input”Wish to write more text(Y/N) : “)
if ch in (‘N’, ‘n’) :
break

file1.writelines(Lst) # writing multiple strings


file.close()

SETTING OFFSETS IN A FILE:


If we want to access data in a random fashion from a data file, then Python
gives us seek() and tell() functions to do so.
(i) The tell() method : This method returns an integer that specifies the
current position of the file object in the file. The position so specified is
the byte position from the beginning of the file till the current position of
the file object.
The syntax of using tell() is:
file_object.tell()
(ii) The seek() method This method is used to position the file object at a
particular position in a file.
The syntax of seek() is:

file_object.seek(offset [, reference_point])
 In the above syntax, offset is the number of bytes by which the
file object is to be moved.
 reference_point 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
By default, the value of reference_point is 0, i.e. the offset is
counted from the beginning of the file. For example, the statement
fileObject.seek(5,0)
will position the file object at 5th byte position from the beginning
of the file.

Application of seek() and tell( ) :


print("Learning to move the file object")
fileobject=open("testfile.txt","r+")
str=fileobject.read()
print(str)
print("Initially, the position of the file object is: ",fileobject. tell())
fileobject.seek(0)
print("Now the file object is at the beginning of the file:
",fileobject.tell())
fileobject.seek(10)
print("We are moving to 10th byte position from the beginning of
file")
print("The position of the file object is at", fileobject.tell())
str=fileobject.read()
print(str)

Output of Program :
Learning to move the file object
roll_numbers = [1, 2, 3, 4, 5, 6]
Initially, the position of the file object is: 33
Now the file object is at the beginning of the file: 0
We are moving to 10th byte position from the beginning of file
The position of the file object is at 10
numbers = [1, 2, 3, 4, 5, 6]

Q. Write a function create_text() to create a text file ‘Practice.txt’.

Ans. def create_text() :


# Function to create a text file and add data
fileobject=open("practice.txt","w+")
while True:
data= input("Enter data to save in the text file: ")
fileobject.write(data)
ans=input("Do you wish to enter more data?(y/n): ")
if ans=='n':
break
fileobject.close()

Q.Write a function display_text() to read text file ‘Practice.txt’ and


display its contents.
Ans. def display_text():
# To display data from a text file
fileobject=open("practice.txt","r")
str = fileobject.readline()
while str:
print(str)
str=fileobject.readline()
fileobject.close()

Q. Write a program to perform reading and writing operation in a text file.


Ans. # Program To perform reading and writing operation in a text file
fileobject=open("report.txt", "w+")
print ("WRITING DATA IN THE FILE")
print() # to display a blank line
while True:
line= input("Enter a sentence ")
fileobject.write(line)
fileobject.write('\n')
choice=input("Do you wish to enter more data? (y/n): ")
if choice in ('n','N'):
break
print("The byte position of file object is ",fileobject.tell()) fileobject.seek(0)
#places file object at beginning of file print()
print("READING DATA FROM THE FILE")
str=fileobject.read()
print(str)
fileobject.close()

OPERATIONS ON BINARY FILES :

THE PICKLE MODULE :

We know that Python considers everything as an object. So, all data types
including list, tuple, dictionary, etc. are also considered as objects.
During execution of a program, we may require to store current state of
variables so that we can retrieve them later to its present state.
Likewise, you may like to store a Python dictionary as an object, to be able to
retrieve later.
To save any object structure along with data, Python provides a module called
Pickle. The module Pickle is used for serializing and de-serializing any Python
object structure.

Serialization is the process of transforming data or an object in memory


(RAM) to a stream of bytes called byte streams. These byte streams in a
binary file can then be stored in a disk or in a database or sent through a
network. Serialization process is also called pickling.

De-serialization or unpickling is the inverse of pickling process where a byte


stream is converted back to Python object.

THE PICKLE MODULE :


 The pickle module deals with binary files. Here, data are not written but
dumped and similarly, data are not read but loaded.
 The Pickle Module must be imported to load and dump data.
 The pickle module provides two methods - dump() and load() to work with
binary files for pickling and unpickling, respectively.
The dump() method This method is used to convert (pickling) Python objects
for writing data in a binary file. The file in which data are to be dumped, needs
to be opened in binary write mode (wb).

Syntax of dump() is as follows:


dump(data_object, file_object)

where data_object is the object that has to be dumped to the file with the file
handle named file_OBJECT.

Example :
import pickle
listvalues=[1,"Geetika",'F', 26]
fileobject=open("mybinary.dat", "wb") pickle.dump(listvalues,fileobject)
fileobject.close()

The load() method:


This method is used to load (unpickling) data from a binary file. The file to be
loaded is opened in binary read (rb) mode.

Syntax of load() is as follows:


Store_object = load(file_object)

Here, the pickled Python object is loaded from the file having a file handle
named file_object and is stored in a new object called store_object.

Example :
import pickle
print("The data that were stored in file are: ")
fileobject=open("mybinary.dat","rb")
objectvar=pickle.load(fileobject)
fileobject.close()
print(objectvar)

Q. Program to perform basic operations on a binary file using pickle module


# Program to write and read employee records in a binary file
import pickle
print("WORKING WITH BINARY FILES")
bfile=open("empfile.dat","ab")
recno=1
print ("Enter Records of Employees")
print()
#taking data from user and dumping in the file as list object
while True:
print("RECORD No.", recno)
eno=int(input("\tEmployee number : "))
ename=input("\tEmployee Name : ")
ebasic=int(input("\tBasic Salary : "))
allow=int(input("\tAllowances : "))
totsal=ebasic+allow
print("\tTOTAL SALARY : ", totsal)
edata=[eno,ename,ebasic,allow,totsal]
pickle.dump(edata,bfile)
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):",bfile.tell())
bfile.close()

Q Program to read the employee records from the file using load() module

Ans. print("Now reading the employee records from the file")


print()
readrec=1
try:
with open("empfile.dat","rb") as bfile:
while True:
edata=pickle.load(bfile)
print("Record Number : ",readrec)
print(edata)
readrec=readrec+1
except EOFError:
pass
bfile.close()

Note :
As each employee record is stored as a list in the file empfile.dat, hence while
reading the file, a list is displayed showing record of each employee.

Q. Write a method countvowels() that reads a text file DIARY.TXT and count
the number of vowels in the file and display it.
Contents of text file "DAIRY.TXT" :
This is my Website.
My name is Parveen.
Ans.
def countvowels() :
file = open("DIARY.TXT", "r")
S = file.read()
v=0
for ch in S :
if ch in 'aAeEiIoOuU': # if ch in [‘a’, ‘e’,’i’, ‘o’,’u’, ‘A’,’E’,’I’,’O’,’U’]
v = v +1
file.close()
print("Number of vowels : ", v )

#------------------------------------------------
OR

def countvowels() :
file = open("DIARY.TXT", "r")
S = file.read()
v=0
for i in range(len(S)) :
if S[i] in 'aAeEiIoOuU': # if S[i] in [‘a’, ‘e’,’i’, ‘o’,’u’, ‘A’,’E’,’I’,’O’,’U’]
v = v +1
file.close()
print("Number of vowels : ", v )

Q. Write a python method countword() that count the number of times


word ‘my’ appear in the
Text file.
Ans.
def countword():
file = open("DAIRY.XT", "r")
S = file.read() # reads entire file as one string
words = S.split() # converts string ‘S’ into list of words in string ‘S’
cnt = 0 # initialize the counter cnt
for w in words : # traversing the list of words
if w == 'My' or w == 'my' : # if w in [ ‘My’, ‘my’] :
cnt = cnt +1
file.close()
print("Number of times 'my' occur ", cnt)
#----------------------------------------------------------------------------------
OR
def countword():
file = open("DAIRY.XT", "r")
S = file.read() # reads entire file as one string
words = S.split() # converts string ‘S’ into list of words in string ‘S’
cnt = 0 # initialize the counter cnt
for i in range(len(words)) : # traversing the list of words using index
if words[i] == 'My' or words[i] == 'my' : # if words[i] in [ ‘my’, ‘My’ ] :
cnt = cnt +1
file.close()
print("Number of times 'my' occur ", cnt)

Q. Write a python code countlines() to count the number of lines that


start with letter ‘A’ or ‘a’ in the text file ‘DAIRY.TXT’.
Ans.
def countlines():
file = open("DAIRY.XT", "r")
lines = file.readlines()
cnt = 0
for L in Lines :
if L[0] == 'A' or L[0] == 'a' : # if L[0] in ‘aA’ :
cnt = cnt +1
print("Number of lines = ", cnt)
file.close()
OR

def countlines():
file = open("DAIRY.XT", "r")
line = file.readline()
cnt = 0
while line :
if line[0] == 'A' or line[0] == 'a' : # if line[0] in ‘aA’ :
cnt = cnt +1
line = file.readline()
print("Number of lines = ", cnt)
file.close()

Q. Write a python function createtext() to create a text file DAIRY.TXT


that contains multiple lines.
Ans.
def createfile():
file = open("DIARY.TXT", "w")
print(“Enter Text ( # to stop ) : \n”)
while True :
line = input( )
if line == ‘#’ :
break;
file.write(line+"\n")
file.close()

Q. Write python program to create a binary file storing the list of marks
obtained by different students in computer science. Program then read
the file and display the marks obtained by them.
Ans.

def creatbinary() :
file = open("Marks.dat", "wb")
list1 = []
while True :
M = float(input("Enter Marks : "))
list1.append(M)
ch = input("Wish to enter More Marks : ")
if ch in ‘nN’ :
break
pickle.dump(list1,file)
file.close()
#----------------------------------------------------------------------
def readbinaryfile() :
file = open("Marks.dat", 'rb')
try :
while True :
list1 = pickle.load(file)
print(list1)
except EOFError :
pass
file.close()
#--------------------------------------------------------------------------------

OR

# writing Dictionary Object into a binary file


# { ‘Amit’:90, ‘Mukesh’:87, ‘Uma’:56 }
Ans.

def createfile():
file = open("Marks.dat", "wb")
d1 = dict()
while True :
nm = input("Enter Name : ")
M = float(input("Enter the marks in CS : "))
d1[nm] = M
ch = input("Wish to enter More Marks (Y/N): ")
if ch in "nN" :
break
pickle.dump(d1, file)
file.close()
#----------------------------------------------------------------
def readfile():
file = open("Marks.dat", "rb")
try :
while True :
d1 = pickle.load(file)
print(d1)
except EOFError :
pass
file.close()
CSV FILE :
Data sharing is one of the major tasks to be carried out , largely through
spreadsheets or databases. A basic approach to share data is through the
comma separated values (CSV) files.

CSV is a simple flat text file in human readable format which is extensively
used to store tabular data in a spreadsheet or database.

Files in the CSV format can be imported to or exported from programs that
store data in tables.

Each line in CSV file is known as record. Each record consists of one or more
fields separated by commas (known as delimiters).

Example : marks.csv

Name,Class,Marks
Manish,12,90
Aman,12,92
Himanshu,12,65

Need of CSV file :

(i) The extensive use of social networking sites and their various
associated applications requires the handling of huge data. The
processing data have complex structure. The CSV organizes data
into a structured form. Hence proper and systematic organization
of large amount of data is done by CSV.
(ii) It makes very easy for Website developers to create applications that
implements CSV.
(iii) CSV files are commonly used as they are easy to read and manage,
small in size and fast to process/transfer.

Advantages of CSV files :

1. CSV files are easy to read and edit manually.


2. CSV files are smaller in size.
3. CSV files are faster to process/Transfer.
4. CSV files are simple to implement and parse.
5. CSV files are easy to generate and import onto a spreadsheet or database.
CSV file handling in python :

1. For working with CSV files in python, there is an in-built module


called ‘csv’. It is used to read and write tabular data in CSV format.
Syntax :
import csv

2. Operations on CSV file :

(i) Writing Data into a CSV file :


(a) For writing data into a CSV file, we have to create a writer
object using file handler.
The writer object is created by using the writer() function of csv
module. The writer object converts the user’s data into a
delimited string.

Syntax :
<csv_writer_object> = csv.writer(file_object, delimiter = ‘,’)

Example : file = open(“marks.csv”, “w”, newline = “”)


csv_w = csv.writer(file, delimiter = ‘,’)

(b) After creating the writer object, write the user’s data into
CSV file by using writerow() function or writerows()
function.

writerow() function is used to write a single row( iterable) into


the CSV file.

Syntax :
<csv_writer>.writerow(<iterable>)

Example : fields = [Name’, ‘Class’, ‘Marks’]


csv_w.writerow(fields)
rec1 = [‘Aman’, 12, 90]
csv_w.writerow(rec1)
NOTE :

(i) When a CSV file is opened in read/write mode then we have to passed
newline argument as “” (Empty String)
By default newline argument has value ‘\r\n’ and therefore , we have
a blank record between two records. To avoid this, it is necessary to
passed newline argument as “”.

(ii) To write multiple records in one go into a CSV file , we can use
writerows() function of csv module.

writerows() function allows to write (iterable of iterables) list of lists


into the CSV file in one go.

Syntax : <csv_writer>.writerows(<iterable of iterables>)

Example :

file = open(“marks.csv”, “w”, newline = “”)

csv_w = csv.writer(file, delimiter = ‘,’)


records = [[‘aman’,34,90], [‘Mukesh’,23,99], [‘Seema’, 7, 56]
csv_w.writerows(records)
Q. Write a python program to create a CSV file ‘Marks.csv’ that stores
name, class and marks of different students and then display the same
file.
Ans.

def createcsv():
f = open("marks.csv", "w", newline = '')
csv_w = csv.writer(f,delimiter = ',') # creating a writer object using file
handle ‘f’
fields = ['Name', "class", "Marks"]
csv_w.writerow(fields) # writing a delimited string or record
in the csv file
while True :
nm = input ("Enter Name : ")
cl = input("Enter Class : ")
M = float(input("Enter Marks : "))
rec = [nm, cl, M]
csv_w.writerow(rec) # pickle.dump(rec,f) for binary file
ch = input("Wish to write more records (Y/N) : ")
if ch in 'nN' :
break
f.close()
print("File Created")

def readcsv():
f = open("marks.csv", "r", newline ='')
records = csv.reader(f)
for r in records :
#print(r)
print(','.join(r))
f.close()

#------ main----------------
import csv
createcsv()
readcsv()
OR
def createcsv():
f = open("marks.csv", "w", newline = '')
csv_w = csv.writer(f,delimiter = ',')
fields = ['Name', "class", "Marks"]
csv_w.writerow(fields)
records = list()
while True :
nm = input ("Enter Name : ")
cl = input("Enter Class : ")
M = float(input("Enter Marks : "))
rec = [nm, cl, M]
records.append(rec)
ch = input("Wish to write more records (Y/N) : ")
if ch in 'nN' :
break
csv_w.writerows(records)
f.close()
print("File Created")

def readcsv():
f = open("marks.csv", "r", newline ='')
records = csv.reader(f)
for r in records :
#print(r)
print(','.join(r))
f.close()

#------ main----------------
import csv
createcsv()
readcsv()
Q. Write a menu driven program that will perform the following tasks :
1. Add a record into a binary file
2. Display all Records
3. Search a record
4. Delete a Record
5. Update a Record

Ans.
""" Menu Driven program to add records in a binary file,
display the records, Search a record, Update a record
and delete a record.
"""
#-------------- Function to add records -------------
def addrecord():
file = open("stud.dat", "ab")
while True :
rn = int(input("Enter the roll number : "))
nm = input("Enter the name : ")
marks = float(input("Enter the marks : "))
rec = [rn, nm, marks] # created a record
pickle.dump(rec,file)
ch = input("Wish to add records(Y/N) : ")
if ch in "Nn" :
break
file.close()
#--------------- Function to display records --------
def displayrec() :
file = open("stud.dat","rb")
print("Rollno\t", "Name\t", "Marks")
try :
while True :
rec = pickle.load(file)
print(rec[0],rec[1],rec[2], sep = "\t")
except EOFError :
pass
file.close()
#----------------------Search a record ---------------
def searchrec():
R = int(input("Enter the roll number : "))
file = open("stud.dat", "rb")
found = 0
try :
while True :
rec = pickle.load(file)
if rec[0] == R :
found = 1
break
except EOFError :
pass
if found == 1 :
print( "Roll Number : ", rec[0])
print(" Name : ", rec[1])
print(" Marks : ", rec[2])
else :
print("Record not found!!!! ")
file.close()

#-----------------Modify a Record -------------


def modifyrec() :
R = int(input("Enter the roll number : "))
file = open("stud.dat", "rb")
found = 0
records = list()
try :
while True :
rec = pickle.load(file)
if rec[0] == R :
found = 1
# accepting new detail
rec[2] = float(input("Enter updated Marks : "))
records.append(rec)
except EOFError :
pass
file.close()
if found == 0 :
print("Record Not Found !!! ")
else :
file = open("stud.dat", "wb")
for rec in records : # records is a list of Lists
pickle.dump(rec, file)
print("Record is succesffully Modified")
file.close()

# ----------------- DELETE A RECORD ------------------


def deleterec():
R = int(input("Enter the roll number : "))
file = open("stud.dat", "rb")
records = list()
try :
while True :
rec = pickle.load(file)
if rec[0] != R :
records.append(rec)
except EOFError :
pass
file.close()

file = open("stud.dat", "wb")


for rec in records : # records is a list of Lists
pickle.dump(rec, file)
file.close()
print("Record is succesffully Deleted")

#----------------- Menu Function ---------------------


def menu() :
print("\t\t MAIN MENU \n")
print("Press 1 : To add records")
print("Press 2 : To Display all records")
print("Press 3 : To Search a record")
print("Press 4 : To Modify a record")
print("Press 5 : To Delete a record")
print("Press 6 : To Exit \n")

#-----------------------Main Block---------------------
import pickle
while True :
menu()
ch = int(input("Enter your Choice : "))
if ch == 1 :
addrecord()
elif ch == 2 :
displayrec()
elif ch == 3 :
searchrec()
elif ch == 4 :
modifyrec()
elif ch == 5 :
deleterec()
elif ch == 6 :
print("Good Bye!!! ")
break
else :
print("Invalid Choice ")

You might also like