Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 111

CLASS :XII

COM /MATH’S /BIO /HUM


SUB: COMPUTE SCI. WITH PYTHON
CODE-[083]
SESSION:2020-21
UNIT -01 –PROGRAMMING AND
COMPUTATIONAL THINKING-II
1- marks question

(a) Write a statement in Python to open a text file WRITEUP.TXT so that new
content can be written in it.
OR
(a)Write a statement in Python to open a text file README.TXT so that existing
content can be read from it.
OR
Write a statement in python to perform the following operations :
1] to open a text file “BOOK.txt” in read mode
2] to open a text file “BOOK.txt” in write mode
Or
(a) Differentiate between file modes r+ and w+ with respect to Python.
2- marks Question

Write a function in python to count the number of lines in a text file ‘STORY.TXT’ ,
which is starting with an alphabet ‘A’ .
OR
Write a method/function DISPLAYWORDS() in python to read lines from a text
file STORY.TXT, and display those words, which are less than 4 characters.
OR
Write a function count_me_my() in python to read the text file “Data.txt” and count the
number of times “me” and “My”.
OR
Write a method/function AEDISP() in python to read lines from a text file WRITER.TXT,
and display those lines, which are starting either with A or starting with E.
OR
Write a method/function ISTOUPCOUNT() in python to read contents from a text file
WRITER.TXT, to count and display the occurrence of the word ‘‘IS’’ or ‘‘TO’’ or ‘‘UP’’.
OR
Write method in Python to read lines from a text file DIARY.TXT, and display those lines,
which are starting with an alphabet ‘P’.
05- marks question
A binary file “Book.dat” has structure [BookNo, Book_Name,
Author, Price].
i. Write a user defined function CreateFile() to input data for a
record and add to Book.dat .
ii. Write a function CountRec(Author) in Python which accepts the
Author name as parameter and count and return number of books by
the given Author are stored in the binary file “Book.dat”
OR
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%
CBSE QUESTION PATTERN OF FILE HANDLING

Considering the following definition of class COMPANY, write a method in


Python to search and display the content in a picked COMPANY.DAT, where
CompID is matching with the value ‘1005’.
class company :
dar_init_(self, CID, NAM) :
self.CompID = CID # compID company ID
self.CName = NAM # CName Company Name
self.Turnover = 1000
def Display (self) :
print self, CompID, “:”, self.CName, “:”, self.Turnover
Concept of File

The usage of a file system is an important thing in the field of


computer science. It is the most common method used to store
required information in various formats.
File system is the best solution to store the information permanently
in a memory device of a computer. 
A Computer File
A computer file is a virtual environment that acts as a container for
various types of information. Consider the real world, we have a lot
of stuffs such as papers and books to store information.
A file is durable in the sense that it remains available for programs to
use after the current program has finished. Computer file can be
considered as the modern counterpart of paper document which
traditionally are kept in office files, library files, etc., 
Concept of File

Data maintained inside the files is termed as persistent data. It means


it is permanent in nature.
Python allow us to read data from and save data to external text files
permanently on secondary storage media.
Need for a data file

The computer has a powerful feature of saving data. As you know


data means raw facts and figures. and meaningful data is known as
information.

These data can be stored in a file. Whenever users need such data,
data can be presented by files.
 
When you develop a program in python, the final output of the
program is not available for future use. Data files serve this purpose.

Python allow us to read data from and save data to external text
files permanently on secondary storage media.
File:-
A file is a stream or sequence of characters/data occupying
named place on the disk where a sequence of related data
is stored.
Flow of Data
File I/O [input/ouput] means Transfer of data from
Secondary Memory to [Hard Disk] to Main Memory or
Vice versa .
Types of File in Python:
Before we discuss file operation we should be aware
of the file types. Python allows us to create and
manage three types of data files.

1- Text file
2- Binary file
3- CSV file
Data File Types
1] Text file  
It is a file that stores information in ASCII characters. In text files, each line of text
is terminated with a special character known as EOL (End of Line) character or
delimiter character. When this EOL character is read or written, certain internal
translations take place.
2] Binary file
It is a file that contains information in the same format as it is held in memory. In
binary files, no delimiters are used for a line and no translations occur
here.   Binary files are used to store binary data such as images, video files, audio
files, etc.
Binary files in Python
Most of the files that we see in our computer system are called binary files.
Example:
•Document files: .pdf, .doc, .xls etc.
•Image files: .png, .jpg, .gif, .bmp etc.
•Video files: .mp4, .3gp, .mkv, .avi etc.
•Audio files: .mp3, .wav, .mka, .aac etc.
•Database files: .mdb, .accde, .frm, .sqlite etc.
•Archive files: .zip, .rar, .iso, .7z etc.
•Executable files: .exe, .dll, .class etc.

For handling such binary files we need a specific type of software to open it.

For Example, You need Microsoft word software to open .doc binary files. Likewise,
you need a pdf reader software to open .pdf binary files and you need a photo
editor software to read the image files and so on.
Text files in Python
Text files don’t have any specific encoding and it can be opened in
normal text editor itself.
Example:
•Web standards: html, XML, CSS, JSON etc.
•Source code: c, app, js, py, java etc.
•Documents: txt, tex, RTF etc.
•Tabular data: csv, tsv etc.
•Configuration: ini, cfg, reg etc.
Data File Operations
The operations performed on a file is called the file
operation. Following is the list of operations can be applied
on a file in python.
Basic file operations :-
1] Opening a File
2] Performing Operations [read , write etc.]
3] Closing a file
Data File Operations
We can process file in several ways such as:
1] creating a file
2] Traversing a file to display contents
3] appending data in a file
4] inserting data in file
5] deleting data from a file
6] Creating a copy of a file
7] updating data in a file etc.
Modes of opening the file :-
Opening and Closing a Text File

Open a File:-
To open a file, you need to use the built-in open function. The open
function returns a file object that contains methods and attributes to
perform various operations on the file.
Syntax :
file_object = open("filename", "mode")

Here,
filename: gives name of the file that the file object has opened.
mode: attribute of a file object tells you which mode a file was
opened in.
Modes of opening the file :-

The access mode is the string which tells in what mode the file
should be opened for operations. There are three different access
modes are available in python.

Reading: Reading mode is crated only for reading the file. The


pointer will be at the beginning of the file.

Writing: Writing mode is used for overwriting the information on


existing file.

Append: Append mode is same as the writing mode. Instead of over


writing the information this mode append the information at the end.
Concept of File mode :

Below is the list of representation of various access modes in python.


Reading Mode
r - Opens a text file for Reading. The file pointer is placed at the
beginning of the file.

rb - Opens a binary file for Reading in binary format. The file pointer
is placed at the beginning of the file.

r+ - Opens a text file for Reading and Writing. The file pointer is
placed at the beginning of the file.

rb+ - Opens a binary file for Reading and Writing in binary format.
The file pointer is placed at the beginning of the file.
Concept of File mode :

Below is the list of representation of various access modes in python.


Writing Mode
W - Opens a text file for Writing. If file doesn’t exist ,creates a new
file.

Wb - Opens a binary file for Writing in binary format. If file doesn’t


exist ,creates a new file.

w+ - Opens a text file for Reading and Writing , If file doesn’t


exist ,creates a new file.

wb+ - Opens a binary file for Reading and Writing in binary format,
If file doesn’t exist ,creates a new file.
Concept of File mode :

Append Mode

a - Opens a text file for appending, the file pointer is at the end of the file ,if the
file is doesn’t exist ,it create new file.

ab - Opens a binary file for appending in binary format, the file pointer is at the
end of the file ,if the file is doesn’t exist ,it create new file.

a+ - Opens a text file for appending and reading. The file pointer is at the end of
the file. the file pointer is at the end of the file ,if the file is doesn’t exist ,it create
new file.

ab+ - Opens a binary file for appending and reading in binary format. The file
pointer is at the end of the file. the file pointer is at the end of the file ,if the file is
doesn’t exist ,it create new file.
Concept of File mode :
Opening and Closing a Text File
Concept of File mode :

List out the basic file modes available in python.

r – to read from the file


w – to write into the file
a – append data into the file already exists
r+/w+ – to perform read and write together
rb/wb/ab – read, write and append data into binary
files
Close() – Closing a file

The close() method of a file object flushes any unwritten


information and closes the file object, after which no more
writing can be done .

Python automatically closes a file when the reference


object of a file is reassigned to another file .
Syntax : Fileobject.close()
The write() Method
It writes the contents to the file in the form of
string. It does not return value. Due to buffering,
the string may not actually show up in the file
until the flush() or close() method is called.

The read() Method


It reads the entire file and returns it contents in
the form of a string. Reads at most size bytes or
less if end of file occurs.if size not mentioned
then read the entire file contents.
Writing to File
Use the write() built-in method to write to an existing file.
Remember that you need to open the file in one of the writing modes
(‘w’, ‘a’ or ‘r+’) first.

1] 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.

Example:
# Python code to create a file
file = open(‘c:\test.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()
Writing to File

NOTE PAD WINDOW


2] writelines() method
For writing a string at a time, we use write method, it can’t be used
for writing a list, tuple, etc into a file .
Sequence data type including strings can be written using writelines()
method. To write multiple lines to a file at once,
use writelines() method. This method accepts list of strings as an
input.

Example
f = open('myfile.txt', 'w')
lines = ['New line 1\n', 'New line 2\n', 'New line 3']
f.writelines(lines)
OUTPUT:
myfile.txt
New line 1
New line 2
New line 3
Reading From File :-
Python provides various methods for reading data from a
file . Lets see:
1] read() : to read the entire data from the file.

2] read(n) : To read ‘n’ characters from the file, starting


from the cursor.

3] readline() :- To read only one line from the file; starts


reading from the cursor up to and including the end of the
character.

4] readlines() :- To read all lines from the file into a list.


Write a python program to create and read the city.txt file
in one go and print the contents on the output screen.
Answer:

# Creating file with open() function


f=open("city.txt","w")
f.write("My city is very clean city.")
f.close()
# Reading contents from city.txt file
f=open("city.txt","r")
dt = f.read()
print(dt)
f.close()
[activity-1] Reading From File :- with read() function
[activity-2] Reading From File :- with read(n) function

OUTPUT:
Enter the Name Ashok Kumar
Enter the Age55
Student In
[activity-3] Reading From File :- with readline() function

OUTPUT:
Enter the NameRajendra
Enter the Age88
1. Student Information
Rajendra
Reading From File :- with readlines() function ]\

OUTPUT:
Enter the Nameram kumar
Enter the Age55
1. Student Information
ram kumar
55
#program to count no. of lines from a text file.#

OUTPUT :
Total No. of Lines in File= 3
#program to input info. Of students and display it.
#python data file : with statement

the above with statement will automatically close the file after the nested
block of code.

The advantage of using with statement is that it is guaranteed to close


the file no matter how the nested block exits.
Appending to File :-
Append means ‘To add to ‘ , so if we want to add more data to a
file which already has some data in it by append mode.
“Open for writing and if it exists, then append data to the end of
file”
When we Use ‘a’ mode to open a file :

1] if the file already exits , it will not be erased . If the file does
not exist , it will be created.

2] When data is written to the file , it will be written at the end of


files current contents.
Appending to File :-

OUTPUT:
Name:-Amit Kumar
Address :- MG road Indore
Job Title : Testing Eng.
Company :-TCS
Job Description:- Testing the Code
Appending to File :-
To append data into a file we must open the file in ‘a+’ mode so that we will
have access to both the append as well as write modes.
Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.write (“Strawberry”)
The above code appends the string ‘Strawberry’ at the end of the ‘test.txt’
file.

OUTPUT
Example :2
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.write (“\nGuava”)
The above code appends the string ‘Apple’ at the end of the ‘test.txt’ file in a new
line.

output
Example :3
fruits = [“\nBanana”, “\nAvocado”, “\nFigs”, “\nMango”]
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.writelines(fruits)The above code appends a list of
data into a ‘test.txt’ file.

OUTPUT
Assignment Based on Text File
1.Write a python programs to create and read city.txt file in one go and print the
contents in the output screen
2.Write a user defined function in Python that displays the number of lines starting
with ‘H’ in the file city.txt. Example if file contains:
Whose woods these are I think know,
His house is in the village through,
He will not see me stoping here
To watch his woods fill up with snow
Then the line count should be : 2
3] Write a method Display_words() in python to read lines from a text file City.txt
and display those words which are less than 4 characters
4] Write a program to count the words “To” and ‘The’ present in text file “city.txt”
5] Write a python method to count the number of lines in a text file.
6] Write a method in Python to read lines from a text file NOTES.TXT, and count
those lines, which are ending with ‘.’ or ‘,’.
7] Write a Python method to count the no.of words in text file
Assignment Based on Text File
8.Write a function to count total no. of char and space in text file
“City.txt”

9.Write a function to count the number of Uppercase and lowercase


alphabets present in a text file “City.txt".

10.Write a method/function ISTOUPCOUNT() in python to read contents


from a text file CITY.TXT, to count and display the occurrence of the word
‘‘IS’’ or ‘‘TO’’ or ‘‘UP’’.
For example : If the content of the file is
The method/function should display
Count of IS TO and UP is 6

11 . Write a python function that copies a text file “Source.txt” onto


“Target.txt” barring the lines starting with a “@” sign.
REVISION OF TEXT FILE
1] read method : lines entered by user…
def read_all():
print("Contents of File=")
my_file=open("d:\\test1.txt", 'r')
data=my_file.read() #read whole contents of file at one go
print(data)
my_file.close()

#2] read contents according given bytes..


def read_char():
print("char by char read(n)=")
my_file=open("d:\\test1.txt", 'r')
print(my_file.read(10))
my_file.close()
REVISION OF TEXT FILE
#3. read contents line by line [one line at a time]
def read_line():
print("line by line=")
my_file=open("d:\\test1.txt", 'r')
print("Firs Line=")
print(my_file.readline())
my_file.close()
#4. Read all lines of file and display it
def read_lines():
print("all lines of file=")
my_file=open("d:\\test1.txt", 'r')
print("Firs Line=")
x = my_file.readlines()
print(x)
print("Line one by one")
for line in x:
print(x)
my_file.close()
seek() and tell() Functions in Python Programming
tell(): In python programming, within file handling concept tell() function is used
to get the actual position of file object. By file object mean a cursor. And it’s
cursor, who decides from where data has to be read or written in a file.
The tell() function, returns the current position of the file pointer(cursor) in a
stream.
seek(): In python programming, within file handling concept seek() function is
used to shift/change the position of file object to required position. By file object
we mean a cursor. And it’s cursor, who decides from where data has to be read or
write in a file.
there are three possible values for start_from --
0 :beginning of file
1 :current position of file
2 :end of file
seek() Functions in Python Programming

OUTPUT:
IT IS UP TO US TO TAKE CARE OF OUR
SURROUNDING. IT IS NOT POSSIBLE ONLY FOR
THE GOVERNMENT TO TAKE RESPONSIBILITY
Cursor Position : 15
TO TAKE CARE OF OUR SURROUNDING. IT IS
NOT POSSIBLE ONLY FOR THE GOVERNMENT
TO TAKE RESPONSIBILITY
tell() Functions in Python Programming

OUTPUT

Cursor Position is : 0
After reading 5 data from file
Cursor Position is : 5
RANDOM ACCESS IN FILES USING TELL() AND SEEK()
seek()—seek() function is used to change the position of the file handle (file pointer)
to a given specific position. File pointer is like a cursor, which defines from where the
data has to be read or written in the file.

For example,
f.seek(–10,1) from current position, move 10 bytes backward
f.seek(10,1) from current position, move 10 bytes forward
f.seek(–20,1) from current position, move 20 bytes backward
f.seek(10,0) from beginning of file, move 10 bytes forward

tell()—tell() returns the current position of the file read/write pointer within the file. Its
syntax is:
f.tell() #where f is file pointer

When you open a file in reading/writing mode, the file pointer rests at 0th byte.
 When you open a file in append mode, the file pointer rests at the last byte.
RANDOM ACCESS IN FILES USING TELL() AND SEEK()
Concept of Relative and Absolute Paths

Relative Path: A relative path is the path that is relative to the working directory
location on your computer. In Program (oceans.py) we have used relative path of
ocean.txt in open function.
Therfore, text file 'oceans.txt' is created and stored in same folder
(current working directory) where we have saved 'oceans.py‘
Example :d:\\ test.txt is relative path.

Absolute Path: An absolute path is a path that contains the entire path to the file
that you need to access. This path will begin with drive of your computer and will
end with the file that you wish to access.
Example:C:\Users\91981\Desktop\oceans.txt
Relative and Absolute Paths
The absolute path is the full path to some place on your
computer.
The relative path is the path to some file with respect to
your current working directory (PWD).

For example:
•Absolute path: C:/users/admin/docs/staff.txt
•If PWD is C:/users/admin/

then the relative path to staff.txt would be:


docs/staff.txt
2] Concept of Binary File….

The binary file refers to a file which is not readable by users


directly. It is stored in a numeric pattern or follows some binary
codes or a file which is processed quicker than text files.

Unlike text files, binary doesn’t have any end-line character or


any character which is going to be translated into machine-
readable form.

The files like images, audio files or video files are examples of
binary files.

Binary files are mainly used for storing records, just as we store
records in a database. It makes it easier to access or modify
the records easily.
Writing and Reading Data from a Binary File

Binary files store data in the binary format (0’s and


1’s) which is understandable by the machine.
So when we open the binary file in our machine, it
decodes the data and displays in a human-readable
format.
Binary file Operation

Python provides the pickle module to write and read data from binary files. To work with
the pickle module, we need to import it in our program using import statement as: import
pickle
Python pickle module is used for serializing and de-serializing python object structures.

The process to converts any kind of python objects (list, dict, etc.) into byte streams (0s
and 1s) is called pickling or serialization or flattening or marshalling.

We can converts the byte stream (generated through pickling) back into python objects by
a process called as unpickling.

So when we want to work on Binary File , conversion of data at the time of reading and
writing Pickle Module is required.
PICKLE MODULE :

What is pickling?
Pickling: The process of converting the structure (lists and
dictionary etc.) into a byte stream just before writing to the file.
This is also called as object serialization.

dump() function: We use dump() method to perform pickling


operation on our Binary Files. It returns the object
representation in byte mode. The dump() method belongs to
pickle module.
PICKLE MODULE :
Unpickling: The reverse conversion of byte stream back to the
structure (lists, dictionary, tuples etc.) refers to unpickling.
Basically it is the reverse operation of pickling. This is also
called de-serialization. We use load() method for unpickling.
This load() function/method also belongs to pickle module.

load() function: In pickle module, load() function is used to read data from a binary
file or file object.

Syntax:
#Syntax_unpickling_in_python
import pickle
pickle.load(file)
File Mode
File Opening Modes:
wb writing only. Overwrites the binary file if exists. If
not, creates a new binary file for writing.

wb+ both writing and reading. Overwrites the binary


file if exits. If not, creates a new binary file for writing.

rb reading only. Sets file pointer at the beginning of


the binary file.

rb+ both reading and writing. Sets file pointer at the


beginning of the binary file

ab for appending. Move file pointer at end of the


binary file. Creates new file for writing, if not exist

ab+ for both appending and reading. Move file pointer


at end. If the binary file does not exist, it creates a
new file for reading and writing.
Binary file operation
1. Open binary file in the required file mode (read mode or write mode).
After importing pickle module we need to open the data file in binary mode. We
need to use alphabet “b” with file file opening mode to open a file in binary mode

Example1:

f1=open("file1.txt","wb")

2] Above statement will open file named file2.txt in read as well as binary


mode. r for read mode and b for binary mode.

f3=open("file2.txt","rb")

3] Close the file.


f1.close( )
Basic Functions in Pickle Module
Ways to write data to a binary file in Python
1). Using dump() function/method
dump(): The method used for writing data to binary file is dump() method. It takes
two arguments ‘file object’ and ‘file‘ as parameters. It returns the object
representation in byte mode. The dump() method belongs to pickle module.

For example, writes the record of a student (roll_no, name, gender and marks) in the
binary file named mybinary.dat using the dump().
We need to close the file after pickling
Program 2-6 Pickling data in Python import pickle
Basic Functions in Pickle Module
Ways to write data to a binary file in Python
1). Using dump() function/method
Basic Functions in Pickle Module
How to Read data from a Binary File in Python | Reading data from binary file
in Python
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 file handle called store_object.
Practical Example :3
Program to read structure , list in binary file :

OUTPUT:
Read Operation
[100, 200, 300, 400]
Binary File Based Assignment
Basic operations on a binary file :
Write or Append Operation in Binary File
Basic operations on a binary file :
READ OR DISPLAY ALL Operation in Binary File
Basic operations on a binary file :
Search Operation in Binary File
Basic operations on a binary file :
UPDATE Operation in Binary File
Basic operations on a binary file :
DELETE OR REMOVE Operation in Binary File
Practice :1
Write a code that Write the information itemcode,amout
according to user choice and then reads from a file “sales.dat”
which has following information [itemcode, amount] display
each record and last find out the the sum of the amount.
Update record in Binary file
• To update record follow these steps: def update():
• Open the file using read mode f = open("Sports.dat","rb+")
• Open another file for a write operation pc = int(input("Player to code to search”))
• Declare a variable for unique value to be tf = 0
updated data= pickle.load(f)
• Place the cursor at the beginning, use seek(0) for record in data:
function to do so if record[0]==pc:
• Use try-except and while loop as explained
record[1]=input("Enter Player Name to
above
• Find the current position of the cursor using
update:")
tell() function record[2]=input("Enter Individual
• Use the same logic as done in search record Score to update:")
and ask values to be update record[3]= input("Enter score to
• Now again place the cursor at current position update:")
using seek() function tf = 1
• Write the data using dump() function break
• remove the old file using remove() function
• rename the temp file with the original file if tf==1:
• Use read logic to check the updated records f.seek(0)
pickle.dump(data,f)
print("Record is updated...")
f.close()
Delete the record
Let’s have look at these steps: def bf_delete():
• Open the file in reading mode f = open("Sports.dat","rb")
• Load data using the load function
data=pickle.load(f)
• Close file f.close()
• Prompt a message to delete a record pc = int(input("Player to code to
with a variable delete a record:"))
• Open file in writing mode f = open("Sports.dat","wb")
• Declare a list object to store data from lst=[ ]
the file for record in data:
• Use for loop and if condition as used in if record[0]==pc:
the update and delete, try-except is not continue
necessary lst.append(record)
• Now in if condition write continue if the pickle.dump(lst,f)
record is found f.close()
• Now append the data into a list object
• Write data using the dump method
• Close the file and read data again
What is an Absolute Path?
An absolute path is a path that describes the
location of a file or folder regardless of the
current working directory; in fact, it is relative to
the root directory. It contains the complete
location of a file or directory, hence the name.
Example:
>>> import os
>>> cwd=os.getcwd()
>>> print(cwd)
C:\Users\INDIAN\AppData\Local\Programs\Python\Python37-32
>>>
Standard input, output, and error streams in python

The three standard streams are described as follows:


1] sys.stdin : When a stream reads from standard input.
2] sys.stdout : Data written to sys.stdout ,appears in your screen.
3] sys.stderr : Error messages are written to sys.stderr.
What is CSV file ?

CSV (Comma Separated Values) is a


simple file format used to store tabular data,
such as a spreadsheet or database.
A CSV file stores tabular data (numbers and
text) in plain text.
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.
More about CSV file
•Every line of the file is called a record. And each record consists of
fields that are separated by commas which are also known as
“delimiter” which is the default delimiter, others include pipe(|),
semicolon(;).
•Given below is a structure of a Normal CSV File separated by a
comma, I am making use of a titanic CSV file.
•Structure
•Passenger ,Id, Survived, Pclass, Name, Sex. Age
•1, 0, 3 Braund, Mr. Owen Harris , male, 22
•2, 1, 1 Cumings, Mrs. John Bradley , female, 38
•3, 1, 3 Heikkinen, Miss. Laina , female, 26
•4, 1, 1 Futrelle, Mrs. Jacques Heath ,female, 35
Example of CSV data :-

CSV Data
•Programming language, Designed by, Appeared, Extension
•Python, Guido van Rossum, 1991, .py
•Java, James Gosling, 1995, .java
•C++, Bjarne Stroustrup, 1983, . cpp

As you can see each row is a new line, and each column is separated with a comma.
This is an example of how a CSV file looks like.
Opening csv file:

•A csv file is opened n the same way as any text file is


opened.

syntax:
fh=open(“stu.csv”,”w”)- to open the file in write mode
fh=open(“stu.csv”,”r”)- to open the file in read mode
Python CSV Module

Python provides a CSV module to handle CSV files. To read/write


data, you need to loop through rows of the CSV. You need to use the
split method to get data from specified columns.
The csv module is used for reading and writing files. It mainly
provides following classes and functions:
•reader()
•writer()
•DictReader()
•DictWriter()
Writing CSV files with writer() 
To write data to a CSV file we use the writer() function. It accepts
the same argument as the reader() function but returns a writer
object (i.e _csv.writer):
Writing in csv file:
• Writing into a csv file involves conversion of the user data into
the writable delimited form and storing it in the form of csv file.
This is done using following three functions:

• 1.csv.writer – returns a writer object which writes data into csv


file.
syntax: writerobject= csv.writer(fileobject)
example : stuwriter=csv.writer(fh)

• 2.
writerobject.writerow() – writes one row of data onto the
writer object
example : stuwriter.writerow(sturec) #sturec=[23,’Rustom’,79]

• 3.
writerobject.writerows()- writes multiple rows of data onto
the writer
example : stuwriter.writerows(sturec) #
sturec=[[11,’Nishtha’,99],[12,’Rudy’,’89.0]]
CSV File Writer Example -1
CSV File Writer Example -2

Example 2: Write into CSV files with csv.writer()


Suppose we want to write a CSV file with the
following entries:
SN,Name,Contribution
1,Linus Torvalds,Linux Kernel
2,Tim Berners-Lee,World Wide Web
3,Guido van Rossum,Python Programming
csv.writer – write data to a csv file
Example 2: Using writerow()

When we run the above program, an innovators.csv file is


created in the current working directory with the given entries.
Next, the csv.writer() function is used to create a writer object.
The writer.writerow() function is then used to write single rows
to the CSV file.
CSV file Parameters

CSV Sample File.


Optional Python CSV reader Parameters
The reader object can handle different styles of
CSV files by specifying additional parameters, some
of which are shown below:
•delimiter specifies the character used to separate
each field. The default is the comma (',').
•quotechar specifies the character used to surround
fields that contain the delimiter character. The
default is a double quote (' " ').
•escapechar specifies the character used to escape
the delimiter character, in case quotes aren’t
used. The default is no escape character.
Example 3 Using writerows()
Example 4: Writing Multiple Rows with writerows()

The output of the program is the same as in Example 1.


Here, our 2-dimensional list is passed to
the writer.writerows() function to write the content of the
list to the CSV file.
•Reading from csv files using csv.reader()
To read from a csv file, we must construct a reader object,
which will then parse the file and populate our Python
object.

Python’s csv module has a method called csv.reader() which


will automatically construct the csv reader object.

We must call the csv.reader() method on an already opened


file object, using open().
How to Read a CSV File with blank delimiter
Example :
def read():
import csv
file=open('f:\\programer.csv', 'rt')
csv_reader = csv.reader(file, delimiter=' ')
for line in csv_reader:
print(line)
read() #function calling

OUTPUT:
['SN,Name,Contribution']
['1,Linus', 'Torvalds,Linux', 'Kernel']
['2,Tim', 'Berners-Lee,World', 'Wide', 'Web']
['3,Guido', 'van', 'Rossum,Python', 'Programming']
How to write/read CSV File with optional argument

OUTPUT
•Writing CSV files with DictWriter() 
DictWriter()
This function returns a DictWriter object. It is
similar to writer object, but the rows are mapped
to dictionary object.
The function needs a file object with write
permission and a list of keys used in dictionary
as fieldnames parameter. This is used to write
first line in the file as header.
The DictWriter object writes a dictionary to a CSV
file. Its syntax is as follows:

DictWriter(fileobj, fieldnames, restval='',


extrasaction='raise', dialect='excel', **fmtparam)
•Writing CSV files with DictWriter() 
The DictWriter provides the following three methods to write
data.

Method Description
writeheader() Writes the header (i.e fieldnames) to the CSV
file and returns None.
writerow(row) Writes a single row of data and returns the
number of characters written. The row must be
a sequence of strings and number.
writerows(rows) Writes multiple rows of data and
returns None. The rows must be a sequence.
•Example 1:T0 Write Dictionary in CSV file
•Example 2 :T0 Write Dictionary in CSV file
•How to Read a CSV as a Dictionary
You can also you use DictReader to read CSV files.
The results are interpreted as a dictionary where the
header row is the key, and other rows are values.

DictReader works almost exactly like reader() but instead of


retuning a line as a list, it returns a dictionary
•How to Read a CSV as a Dictionary
#how to read dictionay in CSV file
def read_dict():
import csv
f= open('f:\\dictcustomers.csv', 'rt')
csv_reader= csv.DictReader(f, escapechar='\\')
for row in csv_reader:
print(row)

OUTPUT:
OrderedDict([('id', '1'), ('name', 'Hannah'), ('address', '4891 Blackwell Street')])
OrderedDict([('id', '2'), ('name', 'Walton'), ('address', '4223 Half and Half Drive')])
OrderedDict([('id', '3'), ('name', 'Sam'), ('address', '3952 Little Street, Akron, Ohio')])
OrderedDict([('id', '4'), ('name', 'Chris'), ('address', '3192 Flinderation Road')])
OrderedDict([('id', '5'), ('name', 'Doug'), ('address', '3236 Walkers Ridge Way')])
•How to Write/Read from CSV as a Dictionary

OUTPUT
Short Revision
End of the chapter

You might also like