100% found this document useful (1 vote)
26 views128 pages

CLASS XII-PYTHON-FILE HANDLING - Resource

The document covers file handling in Python, detailing how to read from and write to data files, including text and binary files. It explains the process of opening, closing, and manipulating files, as well as the use of various file modes and functions for reading and writing data. Additionally, it discusses the importance of file pointers, standard input/output/error streams, and the use of the 'with' statement for file operations.
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
100% found this document useful (1 vote)
26 views128 pages

CLASS XII-PYTHON-FILE HANDLING - Resource

The document covers file handling in Python, detailing how to read from and write to data files, including text and binary files. It explains the process of opening, closing, and manipulating files, as well as the use of various file modes and functions for reading and writing data. Additionally, it discusses the importance of file pointers, standard input/output/error streams, and the use of the 'with' statement for file operations.
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/ 128

INDIAN SCHOOL MUSCAT

CLASS XII
COMPUTER SCIENCE (083)
Chapter : Data File Handling
FILE HANDLING
WRITE

INTRODUCTION
 DATA FILES
 OPENING AND CLOSINGFILES
 READING AND WRITING FILES
 STANDARD INPUT, OUTPUT AND ERROR STREAMS
Introduction

WRITE
 FILE HANDLING is a mechanism by which we can
read data of disk files in python program or write
back data from python program to disk files.
 So far in our python program the standard input in
coming from keyboard an output is going to
monitor i.e. no where data is stored permanent and
entered data is present as long as program is
running BUT file handling allows us to store data
entered through python program permanently in
disk file and later on we can read back the data
DATA FILES
WRITE  It contains data pertaining to a
specific application, for later use. The
data files can be stored in two ways –
 Text File
 Binary File
Text File
 Text file stores information in ASCII OR
WRITE UNICODE character. In text file everything will
be stored as a character for example if data is
“computer” then it will take 8 bytes and if the
data is floating value like 11237.9876 it will take 10
bytes.
 In text file each line is terminated by special
character called EOL. In text file some
translation takes place when this EOL character is
read or written. In python EOL is ‘\n’ or ‘\r’ or
combination of both
Binary files

 It stores the information in the same format as in the


WRITE
memory i.e. data is stored according to its data type so
no translation occurs.
 In binary file there is no delimiter for a new line.
 Binary files are faster and easier for a program to
read and write than text files.
 Data in binary files cannot be directly read, it can be
read only through python program for the same.
Opening File

WRITE
 File can be opened for either – read, write, append.
SYNTAX:

file_object = open(filename)
Or
file_object = open(filename,mode)

** default mode is “read”


Steps in Data File Handling

1. OPENING FILE
WRITE
 We should first open the file for read or write by specifying the
name of file and mode.
2. PERFORMING READ/WRITE
 Once the file is opened now we can either read or write for which
file is opened using various functions available.
3. CLOSING FILE
 After performing operation we must close the file and release the file
for other application to use it.
Opening File

WRITE
myfile = open(“story.txt”)

here disk file is “story.txt memory and its reference


is linked to “myfile” object, now python
program will access “story.txt” through “myfile”
object.
here “story.txt” is present in the same folder
where .py file is stored otherwise if disk file to work
is in another folder we have to give full path.
Opening File
myfile = open(“article.txt”,”r”)
here “r” is for read (although it is by default, other
options are “w” for write, “a” for append)
WRITE

myfile = open(“d:\\mydata\\poem.txt”,”r”)
here we are accessing “poem.txt” file stored in
separate location i.e. d:\mydata folder.
at the time of giving path of file we must use double
backslash(\\) in place of single backslash because in
python single slash is used for escape character and it
may cause problem like if the folder name is “nitin” and we
provide path as d:\nitin\poem.txt then in \nitin “\n” will
become escape character for new line, SO ALWAYS
USE DOUBLE BACKSLASH IN PATH
Opening File
WRITE
myfile = open(“d:\\mydata\\poem.txt”,”r”)

another solution of double backslash is using “r” before


the path making the string as raw string i.e. no special
meaning attached to any character as:

myfile = open(r“d:\mydata\poem.txt”,”r”)
File Handle
WRITE
myfile = open(r“d:\mydata\poem.txt”, “r”)

In the above example “myfile” is the file object or file


handle or file pointer holding the reference of
disk file. In python we will access and manipulate
the disk file through this file handle only.
WRITE File Access Mode
Text File Binary File Mode Description Notes
Mode

‘r’ ‘rb’ Read only File must exists, otherwise Python raises
I/O errors
‘w’ ‘wb’ Write only If file not exists, file is created
If file exists, python will truncate existing data and
overwrite the file.
‘a’ ‘ab’ Append File is in write mode only, new data will be added
to the end of existing data i.e. no overwriting. If file
not exists it is created

‘r+’ ‘r+b’ or ‘rb+’ Read and write File must exists otherwise error is raised Both
reading and writing can take place
w+ ‘w+b’ or ‘wb+’ Write and read File is created if not exists, if exists data will be
truncated, both read and write allowed

‘a+’ ‘a+b’ or ‘ab+’ Write and read Same as above but previous content will be
retained and both read and write.
Closing file
WRITE  As reference of disk file is stored in file handle so to
close we must call the close() function through the
file handle and release the file.
myfile.close()

Note: open function is built-in function used


standalone while close() must be called through file
handle
Reading from File
 To read from file python provide many functions like :
WRITE

 Filehandle.read([n]) : reads and return n bytes, if


n is not specified it reads entire file.
 Filehandle.readline([n]) : reads a line of input. If
n is specified reads at most n bytes. Read bytes in
the form of string ending with line character or blank
string if no more bytes are left for reading.
 Filehandle.readlines(): read all lines and returns
them in a list
EXAMPLE-1: read()
Sample file

WRITE
output

WRITE
EXAMPLE-2:read()
Sample file

WRITE
output

WRITE
EXAMPLE-3:readline()
Sample file

WRITE
output
WRITE

HAVEYOU NOTICED THE DIFFERENCE IN OUTPUT FROM PREVIOUS OUPUT?


WRITE EXAMPLE-4:reading line by line using readline( )
Sample file
output

WRITE
WRITE EXAMPLE-5:reading line by line using for loop
Sample file
output

WRITE
WRITE EXAMPLE-6:Calculatibg size of file with and without EOL
and blank lines.
Sample file
output

WRITE
WRITE EXAMPLE-7: readlines()

Sample file
WRITE
output
WRITE EXAMPLE- 8: Counting the size of file in bytes.

Sample file

output
WRITE
EXAMPLE- 9: Counting the no: of lines in a file.
Sample file

output
WRITE
Writing on to files
 After read operation, let us take an example
of how to write data in disk files. Python
provides functions:
 write ()
 writelines()
 The above functions are called by the file
handle to write desired content.

Name Syntax Description


write() Filehandle.write(str1) Writes string str1 to file referenced by
filehandle
writelines() Filehandle.writelines(L) Writes all string in List L as lines to file
referenced by filehandle.
WRITE
Example-1: write() using “w” mode
WRITE
Example-1: write() using “w” mode
Lets run the
same program
again

Now we can observe that while writing data to file using “w” mode the previous content of existing
file will be overwritten and new content will be saved.

If we want to add new data without overwriting the previous content then we should write using “a”
mode i.e. append mode.
WRITE
Example-2: write() using “a” mode

New content is
added after
previous content
WRITE
Example-3: using writelines()
WRITE
Example-4: Writing string as a record to a file
WRITE
Example-4: Writing string as a record to a file
WRITE
Example-5: To copy the content of one file to
another file
WRITE
Example-4: To copy the content of one file to
another file
Second file is created
WRITE

flush() function
 When we write any data to file, python hold
everything in buffer (temporary memory) and
pushes it onto actual file later. If you want to
force Python to write the content of buffer
onto storage, you can use flush() function.

 Python automatically flushes the files when


closing them i.e. it will be implicitly called by the
close(), BUT if you want to flush before closing
any file you can use flush()
WRITE
Example: Working of flush()

Without flush()

Nothing is in
the file
temp.txt

When you run the above code, program will stopped at


“Press any key”, for time being don’t press any key and go to
folder where file “temp.txt” is created ,open it to see what is
in the file till now.
WRITE
Example: Working of flush()

NOW PRESS
Without flush() ANY KEY
Nothing is in
the file
temp.txt

Now content is stored, because of


close() function contents are flushed
and pushed in the file.
WRITE
Example: Working of flush()

With flush()
All contents
before flush() are
present in file

When you run the above code, program will stopped at


“Press any key”, for time being don’t press any key and go to
folder where file “temp.txt” is created ,open it to see what is
in the file till now.
WRITE
Example: Working of flush()

NOW PRESS ANY KEY


Nothing is in
the file
temp.txt

Rest of the content is written


because of close(), contents are
flushed and pushed in file.
.
WRITE

Removing whitespaces after reading from


file
Nothing is in
 read() and readline() reads data from file and return
the file
it in the form of string and readlines() returns data
temp.txt

in the form of list.


 All these read function also read leading and trailing
whitespaces, new line characters. If you want to
remove these characters you can use functions

 strip() : removes the given character from both ends.


 lstrip(): removes given character from left end
 rstrip(): removes given character from right end
WRITE
Example: strip(),lstrip(),
rstrip()
Nothing is in
the file
temp.txt
WRITE

File Pointer
 Every file maintains a file pointer which tells
Nothing is in
the file
the current position in the file where readingtemp.txt
and writing operation will take.
 When we perform any read/write operation
two things happens:
 The operation at the current position of
file pointer
 File pointer advances by the specified
number of bytes.
WRITE
Example
myfile = open(“ipl.txt”,”r”)
Nothing is in
the file
temp.txt

File pointer will be by default at first position i.e. first character


ch = myfile.read(1))

ch will store first character i.e. first character is consumed,


and file pointer will move to next character
File Modes and Opening position
of file pointer
Nothing is in
WRITE
the file
temp.txt
FILE MODE OPENING POSITION
r, r+, rb, rb+, r+b Beginning of file
w, w+, wb, wb+, w+b Beginning of file (overwrites the file
if file already exists)
a, ab, a+, ab+, a+b At the end of file if file exists
otherwise creates a new file
Standard INPUT, OUTPUT and ERROR STREAM

 Standard Input : Keyboard Nothing is in


the file
WRITE  Standard Output : Monitor temp.txt

 Standard error : Monitor

 Standard Input devices(stdin) reads from keyboard


 Standard output devices(stdout) display output on monitor
 Standard error devices(stderr) same as stdout but normally
for errors only.
Standard INPUT, OUTPUT and ERROR STREAM
 The standard devices are implemented as files
called standard streams in Python and we can
use them by using sys module. Nothing is in
WRITE the file
 After importing sys module we can use temp.txt

standard streams stdin, stdout, stderr


import sys
myfile = open("ipl.txt","r")
line1= myfile.readline()
line2= myfile.readline()
sys.stdout.write(line1+'\n')
sys.stdout.write(line2)
sys.stderr.write("No error found\n")
myfile.close()
“with” statement
 Python’s “with” statement for file handling isNothing
very is in
WRITE
handy when you have two related operations the which
file
temp.txt
you would like to execute as a pair, with a block of
code in between:
with open(filename[, mode]) as filehandle:
file_manipulation_statement
 The advantage of “with” is it will automatically close
the file after nested block of code. It guarantees to
close the file how nested block exits even if any run
time error occurs.
Example
Example

Nothing is in
the file
WRITE
temp.txt
Binary file operations
Nothing is in
WRITE  If we want to write a structure such as list or dictionary
the file
temp.txt
to a file and read it subsequently we need to use the
Python module pickle.
Pickling is the process of converting structure to a
byte stream before writing to a file and while
reading the content of file a reverse process
called Unpickling is to convert the byte stream back
to the original format.
Steps to perform binary file operations

Nothing is in
 First we need to import the module called pickle. the file
WRITE
 This module provides 2 main functions: temp.txt

 dump() : to write the object in file which is loaded in binary


mode
Syntax: dump(object_to_write, filehandle)

 load() : dumped data can be read from file using load()


i.e. it is used to read object from pickle file.
Syntax: object = load(filehandle)
Example: dump()
#Program to demonstrate binary file operations
import pickle
myfile = open(“project.dat”, “wb”) Nothing is in
the file
WRITE
temp.txt

See the content is some


kind of encrypted format,
and it is not in complete
readable form
Example: dump()
#Program to demonstrate binary file operations Nothing is in
the file
WRITE
temp.txt
import pickle
mf = open(“project.dat”, “wb”)
Example: load()
#Program to demonstrate binary file operations
import pickle Nothing is in
WRITE mf = open(“project.dat”, “rb”) the file
temp.txt
Absolute Vs Relative PATH

 To understand PATH we must be familiar with


Nothing is in
the
the file
WRITE
terms: DRIVE, FOLDER/DIRECTORY, FILES. temp.txt
 Our hard disk is logically divided into many parts
called DRIVES like C DRIVE, D DRIVE etc.
Absolute Vs Relative PATH
 The drive is the main container in which we
Nothing is in
the file
WRITE
put everything to store. temp.txt

 The naming format is : DRIVE_LETTER:


 For e.g. C: , D:
 Drive is also known as ROOT DIRECTORY.
 Drive contains Folder and Files.
 Folder contains sub-folders or files
 Files are the actual data container.
Absolute Vs Relative PATH
DRIVE
FOLDER Nothing is in
the file
WRITE
temp.txt
Nothing is in
the file
WRITE
temp.txt
Absolute Path
Nothing is in
WRITE  Absolute path is the full address of any file or folder
the file
temp.txt
from the Drive i.e. from ROOT FOLDER. It is like:
Drive_Name:\Folder\Folder…\filename
 For e.g. the Absolute path
REVENUE.TXT will be
 C:\SALES\2018\REVENUE.TXT
 Absolute path of SEC_12.PPT is
 C:\PROD\NOIDA\Sec_12.ppt
Relative Path

 Relative Path is the location of file/folder from


Nothingthe
is in
the file
WRITE current folder. To use Relative path special symbolstemp.txt
are:
 Single Dot ( . ) : single dot ( . ) refers to current
folder.
 Double Dot ( .. ) : double dot ( .. ) refers to parent
folder
 Backslash ( \ ) : first backslash before(.) and double
dot( .. ) refers to ROOT folder.
Nothing is in
the file
WRITE
temp.txt
Nothing is in
the file
temp.txt
WRITE
Nothing is in
the file
temp.txt
WRITE
BINARY FILE OPERATIONS
# Creating a binary file “student.dat”using list concept.

import pickle
f = open("student.dat","wb")
OUTPUT
ans = 'y'
WRITE Enter roll number: 101
record = [ ]
while ans == 'y‘ : Enter name: Anil
rollno = int(input("Enter roll number:")) Enter marks: 99
name = input("Enter name:") Add more(y/n): y
marks = int(input("Enter marks:")) Enter roll number: 102
data = [rollno, name, marks] Enter name: Sunil
record.append(data) Enter marks: 98
ans=input("Add more(y/n):") Add more(y/n): n
pickle.dump(record, f)
f.close()
BINARY FILE OPERATIONS

Exceptions in Python
Python has many built-in exceptions that are raised when your
program encounters an error (something in the program goes
WRITE wrong).
When these exceptions occur, the Python interpreter stops the
current process and passes it to the calling process until it is
handled. If not handled, the program will crash.
For example, let us consider a program where we have
a function A that calls function B, which in turn calls function C.
If an exception occurs in function C but is not handled in C, the
exception passes to B and then to A.
If never handled, an error message is displayed and our
program comes to a sudden unexpected halt.
BINARY FILE OPERATIONS

WRITE
Catching Exceptions in Python
In Python, exceptions can be handled using
a try statement.
The critical operation which can raise an exception is
placed inside the try clause. The code that handles
the exceptions is written in the except clause.
BINARY FILE OPERATIONS

WRITE
BINARY FILE OPERATIONS
# Reading a binary file “student.dat” and displaying the data.
import pickle
f = open(“student.dat","rb")
print("Contents of student file are:")
while True:
WRITE
try:
stud_rec = pickle.load(f)
for R in stud_rec: OUTPUT
rollno = R[0] Contents of student file are:
name = R[1] 101 Anil 99
marks = R[2] 102 Sunil 98
print(rollno,name,marks)
except EOFError :
break
f.close()
BINARY FILE OPERATIONS
# Searching for a record in the binary file “student.dat” and displaying the data.
import pickle
f = open(“student.dat","rb")
rno = int(input("Enter the roll number to search:"))
found = 0
while True:
try: OUTPUT
WRITE stud_rec = pickle.load(f)
Enter the roll number to search:101
for R in stud_rec: Successful search : 101 Anil 99
if R[0]== rno :
rollno = R[0]
name = R[1] OUTPUT
marks = R[2] Enter the roll number to search:103
print("Successful search : ", rollno, name, marks) Record not found
found = 1
except EOFError :
break
if found == 0:
print("Record not found")
f.close()
BINARY FILE OPERATIONS

#Appending/adding more records in “student.dat”


import pickle
f = open(“student.dat","ab")
ans='y'
record = [ ]
WRITE
while ans =='y': OUTPUT
rollno = int(input("Enter roll number:"))
name = input("Enter name:") Enter roll number:103
marks = int(input("Enter marks:")) Enter name: Aniket
data = [rollno,name,marks] Enter marks:95
record.append(data) Add more(y/n):y
ans = input("Add more(y/n):") Enter roll number:104
pickle.dump(record,f) Enter name: Suhana
print("Records appended!!!") Enter marks:90
f.close() Add more(y/n):n
Records appended!!!
BINARY FILE OPERATIONS

seek() function
When we open a file, the system points to the beginning of the file. Any
read or write will happen from the start. To change the file object’s
position, use seek(offset, whence) function. The position will compute
WRITE by adding offset to a reference point, and the whence argument selects
the reference point. It is useful when operating over an open file. If we
want to read the file but skip the first 5 bytes, open the file, use function
seek(5) to move to where you want to start reading, and then continue
reading the file.
Description:
•Syntax: file_pointer .seek(offset, from_what).
•Offset: In seek() function, offset is required. Offset is the position of
the read/write pointer within the file.
•from_what: This is optional. It defines the point of reference. The
default is 0, which means absolute file positioning.
BINARY FILE OPERATIONS

seek() function

WRITE
BINARY FILE OPERATIONS
seek() method
Example:
WRITE
f.seek(10,0) - from beginning of file move10 bytes forward
f.seek(10,1) - from current position move 10 bytes forward
f.seek(-10,1) - from current position move 10 bytes backward
f.seek(-20,1) - from current position move 20 bytes backward
f.seek(-15,2) - from end of the file move 15 bytes backward

Note: Python 3.x only supports text file seeks from the
beginning of the file. seek() with negative offset and relative
positioning only works when the file is opened in binary mode.
BINARY FILE OPERATIONS

tell() Method
Python File tell() Method : python file can be used to return
WRITE the current position of the file object /position pointer within
the file. This method returns an integer value and takes no
parameter.
Syntax:
x= f.tell()
BINARY FILE OPERATIONS
#Updating/Modifying marks of a record in the binary file "student.dat"
import pickle
lst=[]
f = open("student.dat","rb+")
rno = int(input("Enter the roll number to search:"))
found = 0
WRITE while True :
try:
stud_rec = pickle.load(f)
for i in range(len(stud_rec)):
if stud_rec[i][0]== rno :
print("Name:", stud_rec[i][1])
print("Current mark is :", stud_rec[i][2])
stud_rec[i][2] = int(input("Enter new mark:"))
found = 1
lst.append(stud_rec)
except EOFError:
break
BINARY FILE OPERATIONS
#Updating/Modifying marks of record in the binary file "student.dat“
(continuation…)

if found == 1:
f.seek(0)
for i in range(len(lst)): OUTPUT
WRITE
pickle.dump(lst[i], f) Enter the roll number to search:100
else: Record not found!!!
print("Mark Updated!!!")
else:
print("Record not found!!!") OUTPUT
f.close() Enter the roll number to search:104
Name: Suhana
Current mark is : 90
Enter new mark:96
Mark Updated!!!
BINARY FILE OPERATIONS
How to Rename a File/Directory in Python?
Python os module offers various functions to deal and interact with
the underlying operating system of the particular device.

Python os.rename() function enable us to rename a file or directory,


WRITE
directly from command prompt or IDE.
The os.rename() function alters the name of the source/input/current
directory or file to a specified/user-defined name.
Syntax of Python os.rename() function
Have a look at the below syntax:
import os
os.rename(source,destination)
Eg:
os.rename(“Temp.dat”, “student.dat”)
BINARY FILE OPERATIONS
How to Remove/Delete a file in python?

To delete a file, you must import the OS


module, and run its os.remove() function:
WRITE

Syntax of Python os.remove() function


Have a look at the below syntax:

import os
os.remove(“student.dat”)
BINARY FILE OPERATIONS
#Deleting a record in the binary file "student.dat"
import pickle
import os
f1 = open("student.dat","rb")
f2 = open(“temp.dat","wb")
rno = int(input("Enter the roll number to delete:"))
WRITE found = 0
newlst=[]
while True :
try:
stud_rec = pickle.load(f1)
for R in stud_rec:
if R[0]== rno :
found=1
continue
newlst.append(R)
except EOFError:
break
BINARY FILE OPERATIONS

#Deleting a record in the binary file "student.dat“(continuation….)

pickle.dump(newlst,f2)
f1.close()
WRITE f2.close()
os.remove("student.dat")
os.rename(“temp.dat","student.dat") OUTPUT
if found == 1:
Enter the roll number to delete:100
print("Record Deleted")
Record not found
else:
print("Record not found")

OUTPUT
Enter the roll number to delete:104
Record Deleted
MENU DRIVEN PROGRAM FOR BINARY FILES
OPERATIONS USING SEPARATE FUNCTIONS FOR
EACH FILE OPERATION.

FILE CREATED USING THE CONCEPT OF LIST


Menu driven program using the concept of function for each file operations

WRITE
WRITE
WRITE
WRITE
WRITE
(Updating/Modifying program continuation……….)

WRITE
WRITE
(Deleting a record program continuation……….)

WRITE
WRITE
MENU DRIVEN PROGRAM FOR BINARY FILES
OPERATIONS USING SEPARATE FUNCTIONS FOR
EACH FILE OPERATION.

FILE CREATED USING THE CONCEPT OF DICTIONARY


All binary file binary file operations using the
concept of dictionary

WRITE
WRITE
WRITE
WRITE
WRITE
(Updating/Modifying program continuation ………)

WRITE
WRITE
(Deleting a record program continuation ………)

WRITE
WRITE
STORY.TXT HAS THE FOLLOWING INFORMATION.
CONSIDER THIS FILE FOR THE FOLLOWING
PROGRAMS IN THE NEXT SLIDE(S).

WRITE
Q. Write a function in Python to count the number of lines
in a text file “STORY.TXT” which are starting with the
alphabet “A” or “a”.

WRITE
def countlines():
f = open("STORY.TXT","r")
lines = f.readlines() Output
count = 0 Total lines: 2
for w in lines:
if w[0] == "A" or w[0] == "a" :
count = count + 1
print("Total lines:", count)
f.close()
Q. Write a function in Python to read a text file
“STORY.TXT” and display those words which are less
than 4 characters.

def displaywords(): Output


WRITE A
f = open("STORY.TXT","r") any
line = f.read() is
words = line.split() the
of
for w in words: How
if len(w)<4: are
print(w) all
the
f.close() is
Q. Write a function in Python to read a text file
“STORY.TXT” count the number of times word “the”
used in it and display the count.
def countthe():
WRITE
f = open("STORY.TXT","r")
line = f.read()
Output
words = line.split() The word the is occurring = 1 time(s)
count= 0
for w in words:
if w=="the":
count+=1
print("The word the is occurring =", count,"time(s)")
f.close()
Q. Write a function in Python to read a text file
“STORY.TXT” and count the number of times vowels
appearing in it
(both small letters and capital letters together).
WRITE
def count_vowels():
f = open("STORY.TXT","r")
Output
line = f.read() No of times vowels appearing= 32
words = line.split()
count= 0
for w in words:
for i in range(len(w)):
if w[i] in ['a','e','i','o','u','A','E','I','O','U']:
count+=1
Q. Write a function in Python to check the number of lines in a text file
“STORY.TXT” which are starting with the alphabet “A” or “a” and copy
these lines to another file “RESULT.TXT”.
def copy():
f1 = open("STORY.TXT","r")
f2 = open("RESULT.TXT",“w")
WRITE
lines = f1.readlines()
done=0 Output
for w in lines: RESULT.TXT, file created
if w[0]=='A' or w[0]=='a':
f2.write(w)
done=1
if done==1:
print("RESULT.TXT, file created" )
f1.close()
f2.close()
CSV File handling in Python
 CSV is a simple file format used to store tabular data, such as a
spreadsheet or database.
WRITE
 Files in the CSV format can be imported to and exported from
programs that store data in tables, such as Microsoft Excel or
OpenOffice Calc.
 CSV stands for "comma-separated values“.
 A comma-separated values 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
Why to use csv file?
 CSV file formats are plain text format, and easy for
website developers to create applications that
WRITE implement CSV.
 CSV is faster to use.

 CSV is smaller in size.

 CSV is easy to generate and import onto a spreadsheet


or database.
 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 file handling in Python
WRITE
 Toperform read and write operation with CSV file, we must
import csv module.
 open() function isusedto open file, and return file object.
Creating/Writing to a CSV File
 To write to CSV file in Python,we can use the csv.writer()
function. The csv.writer() function returns a writer object that
converts the user’s data into a delimited string. This string can
WRITE
later be used to write into CSV files using the writerow()
function.
 In order to write to a CSV file, we create a special type of object
to write to the CSV file “Writer object”, which is defined in the
CSV module, and which we create using the writer()function.
 The writerow() method allows us to write a list of fields to the
file. The fields can be strings or numbers or both. Also, while
using writerow(). You do not need to add a new line character to
indicate the end of line;writerow() does it for you as necessary.
Q. Write a function create_csv() to create a CSV file “Marks.csv”
to store the student data(Name, Class, Year
and Percent).
def create_csv():
fields=['Name','Class','Year','Percent'] # field names
rows=[ ]
WRITE lst=[ ]
ans='y'
while ans=='y':
Name=input("Enter your name:")
Class = input("Enter the class:")
Year = input("Enter the year:")
Percent= input("Enter the percentage:")
lst=[Name,Class,Year,Percent]
rows.append(lst)
ans=input("Do you want to add more(y/n):")
import csv
f= open(“emp.csv","w“)
csv_w = csv.writer( f)
rows=[ ]
lst=[ ]
WRITE
ans='y'
while ans=='y':
empno=int(input("Enter Employee number:"))
name = input("Enter name:")
salary = float(input("Enter salary:"))
lst=[empno,name,salary]
rows.append(lst)
ans=input("Do you want to add more(y/n):")
for i in rows:
csv_w.writerow(i)
print("File created")
OUTPUT
Enter your name: Akhil
WRITE Enter the class: XII
Enter the year:2005
Enter the percentage:78
Do you want to add more(y/n):y
Enter your name: Sunil
Enter the class: XI
Enter the year:2006
Enter the percentage:98
Do you want to add more(y/n):n
File created
Reading fro m a CSV file
WRITE
 import csv module
 Use open() to open csv file, it will return file object.
 Pass this file object to reader object.
 Perform operation you want
WRITE Q . Write a function read_csv() to read a CSV file
“Marks.csv” and display the data stored in it.

def read_csv():
f = open("Marks.csv","r") # opens file in read mode
csv_r = csv.reader( f, delimiter =',') # reader() function reads the file object
for row in csv_r: # reading the Marks.csv file record by record
print(row)
f.close() OUTPUT
['Name', 'Class', 'Year', 'Percent']
[ 'Akhil', 'XII', '2005', '78']
['Sunil', 'XI', '2006', '98']
WRITE Q . Write a function search_csv() to search for a record in a
CSV file “Marks.csv” and display it.
def search_csv():
f = open("Marks.csv","r") # opens file in read mode
csv_r = csv.reader(f, delimiter =',') # reader() function reads the file object
name = input("Enter the name to be searched :")
found=0
# reading the Mark.csv file record by record
for row in csv_r: OUTPUT
if row[0]== name: Enter the name to be searched :Sunil
print(row) [‘Sunil', 'XI', '2006', '98']
found=1
OUTPUT
if found==0:
Enter the name to be searched :Sunitha
print("Record not found") Record not found
f.close()
WRITE Q . Write a function append_csv() to append records in a
CSV file “Marks.csv”.
def append_csv():
rows=[]
lst=[]
ans='y'
while ans=='y':
Name=input("Enter your name:")
Class = input("Enter the class:")
Year = input("Enter the year:")
Percent= input("Enter the percentage:")
lst=[Name,Class,Year,Percent]
rows.append(lst)
ans=input("Do you want to add more(y/n):")
WRITE
Continuation of append_csv() function……

with open("Marks.csv","a",newline='') as f:
csv_w = csv.writer( f, delimiter = ',')
for i in rows:
csv_w.writerow(i)
print("Record(s) appended") OUTPUT
Enter your name: Vimal
Enter the class: XI
Enter the year:2007
Enter the percentage:94
Do you want to add more(y/n):n
Record(s) appended
Q . Write a function modify_csv() to modify records in a CSV file “Marks.csv ”.
def modify_csv():
f= open("Marks.csv","r") # opens file in read mode
csv_r = csv.reader(f, delimiter=',') # reader() function reads the file object
name = input("Enter the name to be searched :")
found=0
lst=[ ]
for row in csv_r: # reading the Marks.csv file record by record
if row[0]== name:
row[1] = input("Enter the new class:")
row[2] = input("Enter the new year:")
row[3] = input("Enter the new percentage:")
found=1
print(“Record Modified”)
lst.append(row)
Continuation of modify_csv() function……….

f.close()
with open("Marks.csv","w", newline =‘ ') as f:
csv_w = csv.writer(f, delimiter=',')
for i in lst: OUTPUT
csv_w.writerow(i) Enter the name to be searched :Sunil
Enter the new class: XI
if found==0: Enter the new year: 2008
print("Record not found") Enter the new percentage:99
Record Modified

OUTPUT
Enter the name to be searched : Abhilash
Record not found
Q . Write a function delete_csv() to delete a record in a CSV file “Marks.csv ”.

def delete_csv():
f1= open("Marks.csv","r") # opens Marks.csv file in read mode
f2= open("Temp.csv","w",newline=‘ ') # opens Temp.csv file in write mode
csv_r = csv.reader(f1,delimiter=',') # reader() function reads the file object
csv_w = csv.writer(f2,delimiter=',')
found=0
name=input("Enter the name to be deleted :")
for row in csv_r: # reading the Marks.csv file record by record
if row[0]== name:
found=1
print("Record Deleted")
continue
csv_w.writerow(row)
Continuation of delete_csv() function……….

f1.close()
f2.close()
os.remove("Marks.csv")
os.rename("Temp.csv","Marks.csv")
if found==0: OUTPUT
Enter the name to be deleted :Sunil
print("Record not found") Record Deleted

OUTPUT
Enter the name to be deleted : Subash
Record not found

You might also like