[go: up one dir, main page]

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

File Handling

The document discusses file handling in Python. It begins by explaining the need for data files and how Python allows reading from and writing to files. It then describes the two main file types - text files and binary files. The rest of the document discusses various file operations like opening, closing, reading, writing, appending, and comparing different reading methods like read(), readline(), and readlines(). It provides examples of code to perform common file operations and discusses some important concepts that may appear in CBSE exams.

Uploaded by

bhardwajparth137
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)
143 views44 pages

File Handling

The document discusses file handling in Python. It begins by explaining the need for data files and how Python allows reading from and writing to files. It then describes the two main file types - text files and binary files. The rest of the document discusses various file operations like opening, closing, reading, writing, appending, and comparing different reading methods like read(), readline(), and readlines(). It provides examples of code to perform common file operations and discusses some important concepts that may appear in CBSE exams.

Uploaded by

bhardwajparth137
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/ 44

PYTHON FOR COMPUETR SCIENCE

File handiling

For

Class – XII

KAPIL SEHGAL
KAPIL SEHGAL (P.G.T. (CS) K.V. NO2 Delhi Cantt,
Need for data file
• The data stored with in a file is known as persistent data because
this data is permanently stored in the system.
• Python provides reading and writing capability of data files.
• We save the data in the files for further use.
• As you save your data in files using word, excel etc. same thing we
can do with python.
• “A File is a collection of characters in which we can perform read and write functions. And also
we can save it in secondary storage.”

User (Random Access Memory) Hard Disk

KAPIL SEHGAL
FILE TYPES
File are of two types –
1. Text File: A text file is sequence of line and line is the sequence of characters and this file is saved
in a permanent storage device. Although in python default character coding is ASCII but by using
constant „U‟ this can be converted into UNICODE. In Text File each line terminates with a special
character which is EOL (End Of Line). These are in human readable form and these can be created
using any text editor.

2. Binary File: Binary files are used to store binary data such as images, videos audio etc. Generally
numbers are stored in binary files. In binary file, there is no delimiter to end a line. Since they are
directly in the form of binary hence there is no need to translate them. That‟s why these files are
easy and fast in working.

KAPIL SEHGAL
Data File Operations
Data File Operations
1. Opening a File
2. Perform Operations (i.e. Read or Write etc.)
3. Closing the File
Beside above operations there are some more operations can be done on files.-
• Creating of Files
• Traversing of File
• Appending Data into file.
• Inserting Data into File.
• Deleting Data from File.
• Copying of File.
• KAPIL
Updating Data into File.
SEHGAL
Opening & Closing Files
• We need a file variable or file handle to work with files in Python.
• This file object can be created by using open( ) function or file( ) function.
• Open( ) function creates a file object, which is used later to access the file using the functions
related to file manipulation.
• Its syntax is following -
<file_object>=open(<file_name>,<access_mode>)
<file_object>.close()
Write to file
Python
(Save)
External
Basic operations Program
File
(Secondar
y Storage)
1. Write into File Read
2. Read From File. from file
(Load)
KAPIL SEHGAL
Simple program

Normal Program File Creation Programe


name=input(“Enter name “) file=open(“sample.txt”,”w”)
print(nm) name=input(“Enter name “)
file.write(name)

Modes of open a File File Reading Programe


“w” : Creating a new file file=open(“sample.txt”,”r”)
“r” : Reading an existing file data=file.read()
“a” : Append into file. print(data)

KAPIL SEHGAL
Append mode

Normal Program File Creation Programe


name=input(“Enter name “) file=open(“sample.txt”,”w”)
print(nm,ad) str=input(“Enter string “)
Append in File file.write(str)
file=open("sample.txt","a") file.close()
str="This is the line \n" File Reading Programe
data=file.write(str) file=open("sample.txt","r")
Modes of open a File file.close() data=file.read()
“w” : Creating a new file print(data)
“r” : Reading an existing file file.close()
“a” : Append
KAPIL SEHGAL into file.
Writelines method

file=open("sample.txt","w")
lst=["Computer Science \n","Physics \n","Mathematics \n","Chemistry \n","Hindi \n","English \n"]
file.writelines(lst)
print("Data Write Successfully ")
file.close()
Read n methods
file=open("sample.txt","r")
data=file.read(5)
file=open("sample.txt","r") print(data, " ")
data=file.read(5) data=file.read(5)
print(data, " ") print(data, " ")
file.close() data=file.read(5)
print(data, " ")
KAPIL SEHGAL file.close()
Readline method

Readline methods read one line at a time. When file is open, by default file pointer is always at first
character of file (or first line)

New.txt Program to read a file line wise Output

Computer Science file=open("new.txt","r")


>>>
Physics line=file.readline()
Computer Science
Chemistry print(line)
Mathematics line=file.readline() Physics
These
print(line)
are the
line=file.readline() Chemistry
Compulsory
Subjects. print(line)
KAPIL SEHGAL file.close()
Readlines methods
Readlines methods reads all lines in one go and store in list i.e. one line as one element of list.

New.txt Program to read a file with readlines method Output

Computer Science file=open("new.txt","r")


Physics line=file.readlines() ['Computer Science \n', 'Physics
Chemistry print(line) \n', 'Chemistry \n',
Mathematics file.close() 'Mathematics\n']
>>>

KAPIL SEHGAL
Compares between read() and readlines()
Similarity

read() method and readlines() method both extract entire data from file in one go

Difference

read() method extracts entire data into a single string variable. But readlines() method extracts entire data
into form of list of string, it means each line of text file will be an element of List and in form of String.

New.txt Output with read() Output with readlines()


Computer Science Computer Science ['Computer Science \n', 'Physics
Physics Physics \n', 'Chemistry \n',
Chemistry Chemistry 'Mathematics\n']
Mathematics Mathematics >>>
KAPIL SEHGAL
Read functions to read data from files
There are four read functions

1. read() :- Read the entire file in one go and store data into string form
2. read(n) :- Read the n characters from current location of file pointer in file. (When file is open that
time file pointer be at first position.
3. readline() :- Read the file line by line and store line into string form
4. readlines() : Read the entire file in one go and store in form of List of String i.e. One line will be
one element of list and that element in form of string.

Write functions to read data from files


There are two write functions

1. write() :- Write the string into file, it takes only one string type parameter.
2. writelines() : Write the list into file, one element of string in one line.
KAPIL SEHGAL
Important programs – cbse exam based

Write a program to write five Write a program to read a file and display size of
names into file using file in bytes
writelines
Let the file “new.txt” Contains Program
file=open("new.txt","w")
lst=[] Hello Students how are you? file=open("new.txt","r")
for i in range(0,5): I hope you all are fine. data=file.read()
nm=input("Enter name ") size=len(data)
lst.append(nm+"\n") print("Size of File in Bytes ", size)
file.writelines(lst) file.close()
file.close()
Output.

Size of File in Bytes 52


KAPIL SEHGAL
Important programs
Let the file “new.txt” Contains
Write a program to read Write a program to read
Hello Students how are you?
a file and count how a file and count how many
I hope you all are fine.
many words in it. words starts with “a”
Write a program to read a file and file=open("new.txt","r")
file=open("new.txt","r")
print number of lines in a file data=file.read()
data=file.read()
file=open("new.txt","r") lst=data.split() lst=data.split()
data=file.readlines() totalwords=len(lst) count=0
nol=len(data) print(“Total words : ", totalwords) for i in lst:
print(“Number of Lines ", nol) file.close() if (i[0]=='a' or i[0]=='A'):
count=count + 1
file.close()
print("Total words ",count)
Output. Output. file.close()

Number of Lines 2 Total words : 11 Output.

KAPIL SEHGAL Total words : 2


“x” mode to open a file
When we open a file in “w” mode then Python open a fresh file, if it is already exist then overwrite it
without any warning. Instead of using “w” mode, we can use “x” mode.

Like “w” mode “x” mode also open the fresh file but unlike “w” mode, “x” mode do not overwrite file if
it is already exist but it will show run time error.
For Ex. file=open("new.txt","x")
str=input("Enter String ")
file.write(str)
Error Message file.close()

RESTART: C:\Users\Kapil\AppData\Local\Programs\Python\Python35\createfile.py
Traceback (most recent call last):
File "C:\Users\Kapil\AppData\Local\Programs\Python\Python35\createfile.py", line 1, in <module>
file=open("new.txt","x")
FileExistsError: [Errno 17] File exists: 'new.txt'
KAPIL SEHGAL
Flush method
flush() method is an inbuilt method in Python, it is used to clear/flush the internal buffer, it is best
practice while working with file handling in Python, the internal buffer can be cleared before
writing/appending the new text to the file.
Input write() flush() File
User Data R.A.M. Buffer Permanent
file.close() Storage
Without flush() With flush()
file=open("new.txt","w") file=open("new.txt","w")
str=input(“First Interruption ") str=input("First Interruption ")
file.write("one") file.write("one")
file.write("Two") file.write("Two")
st=input(“Second Interruption") file.flush()
file.write("three") st=input(“Second Interruption ")
file.close() file.write("three")
KAPIL SEHGAL file.close()
open a file through “with”
We can also open a file through “with” keyword. Using this way we don‟t need to close file.

Program through open method Program through with

file=open("new.txt","r") with open("new.txt","r") as file :


line=file.readlines() Line=file.readlines()
print(line) print(line)
file.close()

KAPIL SEHGAL
File pointer
A file pointer is simply a marker which keeps track of the number of bytes read or written in a
file. This pointer automatically moves after every read or write operation.

When a file is opened the file pointer points at the beginning of the file. The write() function begins
writing at the current file position and then increments the file pointer. For example, the following
figure shows the position of file pointer after each write operation.

There are two methods to maintain file pointer


tell() :- tell function returns the current position of file pointer.

seek(offset) :- seek(offset) function moves the file pointer to the given offset from the origin

In this image of file we seen the file pointer at 13

KAPIL SEHGAL
Let the file “new.txt” Contains Tell & seek method program
Hello Students how are you?
I hope you all are fine.

Program for tell() methods Program using seek() method

file=open("new.txt","r")
file=open("new.txt","r")
location=file.tell() Output data=file.read(5)
Output
print(location) print(data)
data=file.read(5) 0 data=file.read(3) Hello
print(data)
print(data) Hello St
file.seek(15)
location=file.tell() 5 data=file.read(3) how
print(location) St print(data) hop
data=file.read(3) 8 file.seek(32)
data=file.read(3)
print(data) print(data)
location=file.tell() file.close()
print(location)
KAPIL SEHGAL
Important programs

Write a program to read Write a program to read


Let the file “new.txt” Contains a file and count how many a file and count how many
lines starts with “a” words ends with “a”
TXT files are useful for
storing information in file=open("new.txt","r")
file=open("new.txt","r")
plain text with no special data=file.readlines()
data=file.readlines()
formatting beyond basic fonts count=0
count=0
and font styles. The file is for i in data:
for i in data:
commonly used for recording if (i[-2]=='a' or i[-
if (i[0]=='a' or i[0]=='A'):
notes, directions, and other 2]=='A'):
count=count + 1
similar documents that do not count=count + 1
print("Total Lines ",count)
need to appear a certain way print("Total words ",count)
file.close()
file.close()
Output. Output.
KAPIL SEHGAL
Total Lines : 1 Total Lines : 0
Important programs
Write a program to read a file Write a program to read a file
and count how many words of and and print only digits and
Let the file “new.txt” Contains length 5 (n) numbers

TXT files are useful for


file=open("new.txt","r")
storing information in file=open("new.txt","r")
data=file.read()
plain text with no special data=file.read()
count=0
formatting beyond basic fonts for i in data:
words=data.split()
and font styles. The file is if (i.isdigit()):
for i in words:
commonly used for recording print(i)
if (len(i)==5):
notes, directions, and other file.close()
count=count + 1
similar documents that do not
print("Total words of length 5 : ",count)
need to appear a certain way
file.close() Output.
No output because text file
Output. new.txt does not contains
KAPIL SEHGAL number or digits
Total words of length 5 : 5
Important programs
Write a program to read a file Write a program to read a file
and print those lines which called “new.txt” and copy all
Let the file “new.txt” Contains starts with „s‟ along with line the content to “new1.txt”
NUMBER
TXT files are useful for file=open("new.txt","r")
storing information in data=file.readlines() file=open("new.txt","r")
plain text with no special count=0 file1=open("new1.txt","w")
formatting beyond basic fonts for i in data: data=file.read()
and font styles. The file is count=count+1 file1.write(data)
commonly used for recording if (i[0] in ['s','S']): file.close()
notes, directions, and other print(count,i) file1.close()
similar documents that do not file.close()
need to appear a certain way
Output.
2 storing information in

KAPIL SEHGAL 8 similar documents that do not


Important programs
Write a function to read a file Write a function to read a file
called “new.txt” and copy all called “new.txt” and copy all
Let the file “new.txt” Contains the words which start with „s‟ the words which start with „s‟
copy to “new1.txt” content to “new1.txt”
TXT files are useful for
storing information in file=open("new.txt","r") def copyfile():
plain text with no special file1=open("new1.txt","w") file=open("new.txt","r")
formatting beyond basic fonts data=file.read() file1=open("new1.txt","w")
and font styles. The file is words=data.split() data=file.readlines()
commonly used for recording for i in words: for i in data:
notes, directions, and other if (i[0] in ['s','S']): if (i[0] in ['s','S']):
similar documents that do not file1.write(i) file1.write(i)
need to appear a certain way file1.write(" ") file1.write(" ")
file.close() file.close()
file1.close() file1.close()
copyfile()
KAPIL SEHGAL
More modes to open a file
More modes to open a file
1. “w+” : Open a file for write and read. (But first Write then Read in same file same program)
2. “r+” : Open a file for read and write (But first Read and then Write in same file same program
Example of “w+” mode Example of “r+” mode
file=open("new.txt","w+")
file.write("I am a students of Class 12 C Science") Program for overwrite first five character by *****
file.seek(0)
data=file.read() file=open("new.txt","r+")
print(data) data=file.read()
file.close() file.seek(0)
file.write("*****")
file.close()

KAPIL SEHGAL
Important programs for assignment
1. Write a function to read a file called “new.txt” and count how many “the” word in it.

2. Write a function to read a file and count how many word „Do”. “Do” will be in any case
[“DO”,”do”,‟Do”,”dO”]

3. Write a function to read a file “new.txt” and copy only those lines which ends with „s‟ or “S” to
another file “new1.txt”

4. Write a program to read a file “new.txt” print number of characters in each line.

5. Write a function counteven() to read a file and count how many even number in file “new.txt”

6. Write a program to read a file and count & print only vowels store in it.
KAPIL SEHGAL
Important programs for assignment
Write a program to read a file and count & print only vowels store in it.

file=open("new.txt","r")
data=file.read()
count=0
v=[]
for i in data:
if i in ['a','e','i','o','u','A','E','I','O','U']:
if i not in v:
v.append(i)
count=count+1
file.close()
print(v)
print("Number of Vowel ",count)

KAPIL SEHGAL
Binary file
1. To handle binary file operation, we need a special library called “pickle”

2. Installation of “pickle” library, we write :


pip install pickle-mixin
3. In binary file using pickle library, we can read and write various objects
(like : list, tuple, dictionary etc)

4. Method to write different objects in binary file : dump()

5. Method to read different objects from binary file : load()

6. Mode for Creating a binary file (Fresh File) : wb

7.KAPIL
Mode for Reading a binary file (Existing File ) : rb # here b indicate binary
SEHGAL
Binary file programs
Write a program to create a binary Write a program to create a binary
file using dictionary data file using list and tuple
import pickle import pickle
with open("new.dat","wb") as file: with open("new.dat","wb") as file:
s1={"name":"Ram","Class":"12C"} l1=[10,20,30,40,50]
s2={"name":"Mohan","Class":"12C"} t1=(50,60,70,80)
pickle.dump(s1,file) pickle.dump(l1,file)
pickle.dump(s2,file) pickle.dump(t1,file)

Write a program to read binary file Write a program to read a binary file
using dictionary data using list and tuple
import pickle import pickle
with open("new.dat","rb") as file: with open("new.dat","rb") as file:
d1=pickle.load(file) list=pickle.load(file)
d2=pickle.load(file) tuple=pickle.load(file)
print(d1) print(list)
print(d2)
KAPIL SEHGAL print(tuple)
Binary file programs
Create a binary file with multiple read a binary file with multiple objects
objects import pickle
mainlist=[]
import pickle with open("new.dat","rb") as file:
with open("new.dat","wb") as while True:
file: try:
l1=[10,20,30,40,50] list=pickle.load(file)
l2=[60,70,80,90,100] mainlist.append(list)
l3=[110,120] print(list)
l4=[130,140,150] except EOFError:
pickle.dump(l1,file) break
Output.
pickle.dump(l2,file) print(mainlist)
pickle.dump(l3,file) [10, 20, 30, 40, 50]
pickle.dump(l4,file) [60, 70, 80, 90, 100]
[110, 120]
[130, 140, 150]
KAPIL SEHGAL [[10, 20, 30, 40, 50], [60, 70, 80, 90, 100], [110, 120], [130, 140, 150]]
Append in binary file

w.a.p. to append a list into binary file read a binary file with multiple objects
import pickle
import pickle with open("new.dat","rb") as file:
with open("new.dat",“ab") as file: list=pickle.load(file)
l1=[110,210,310,410,510] tuple=pickle.load(file)
pickle.dump(l1,file) list1=pickle.load(file)
pickle.dump(t1,file) Read object from binary file print(list)
print(tuple)
import pickle print(list1)
with open("new.dat","rb") as file:
while True:
try:
var=pickle.load(file)
print(var)
except EOFError:
KAPIL SEHGAL break
String write read and append in binary file
Write append
import pickle
import pickle with open("new.dat","ab") as file:
with open("new.dat","wb") as file: s1="This is Vidisha"
s1="This is Mumbai" s2="This is Jhansi"
s2="This is Delhi" s3="This is Ujjain"
s3="This is Bhopal" pickle.dump(s1,file)
pickle.dump(s1,file) read
pickle.dump(s2,file)
pickle.dump(s2,file) pickle.dump(s3,file)
import pickle
pickle.dump(s3,file)
with open("new.dat","rb") as file:
while True:
try:
str=pickle.load(file)
print(str)
except EOFError:
KAPIL SEHGAL break
search in binary file
Write a program to search object in to the Write a program to search String in Binary
binary files file contains strings.
import pickle
import pickle with open("new.dat","rb") as file:
rlist=[110,210,310,410,510] # list for search str=input("Enter String to Search ")
with open("new.dat","rb") as file: flag=0
while True: while True:
try: try:
list=pickle.load(file) str1=pickle.load(file)
if (str1==str):
if (list==rlist): print ("Search Successful ")
print(list) flag=1
print("Data Found ") break
else: except EOFError:
print(list) break
except EOFError: if flag==0:
print("Search Unsuccessful")
break
KAPIL SEHGAL
Binary file programs
write a program to read a Binary file “new.dat” which contains list and tuple and find
the sum of the elements of list and tuple.

import pickle import pickle


with open("new.dat","rb") as file: with open("new.dat","wb") as file:
sum=0 l1=[10,20,30,40,50]
while True: l2=(60,70,80,90,100)
try: l3=[110,120]
var=pickle.load(file) l4=(130,140,150)
for i in var: pickle.dump(l1,file)
sum = sum + i pickle.dump(l2,file)
except EOFError: pickle.dump(l3,file)
break pickle.dump(l4,file)
print("Sum of elements of list ",sum)

Output.
KAPIL
SumSEHGAL
of elements of list 410
Binary file programs
write a program to read a Binary file “new.dat” modify the specific oBject
create update
import pickle
import pickle record=[]
with open("new.dat","wb") as file: oldstr=input("Enter String to Replace ")
s1="This is Vidisha" newstr=input("Enter New String ")
with open("new.dat","rb+") as file:
s2="This is Jhansi" while True:
s3="This is Ujjain" try:
s4=[10,20,30,"Ram","Krishna"] read str=pickle.load(file)
record.append(str)
s5=(50,60,70) import pickle except EOFError:
s6={"Name":"Ram","Age":25} with open("new.dat","rb") as file: break
pickle.dump(s1,file) while True: count=-1
pickle.dump(s2,file) for i in record:
try: count=count+1
pickle.dump(s3,file) str=pickle.load(file) if (i==oldstr):
pickle.dump(s4,file) print(str) record[count]=newstr
pickle.dump(s5,file) except EOFError: file.seek(0)
pickle.dump(s6,file) for i in record:
KAPIL SEHGAL
break pickle.dump(i,file)
Binary file programs
write a program to read a Binary file “new.dat” modify the specific oBject
update
create import pickle
import os
import pickle oldobject="This is Vidisha"
with open("new.dat","wb") as file: newobject=["This","is","Vidisha"]
s1="This is Vidisha" tfile=open("temp.dat","wb")
s2="This is Jhansi" with open("new.dat","rb") as file:
read while True:
s3="This is Ujjain" try:
pickle.dump(s1,file) import pickle objread=pickle.load(file)
pickle.dump(s2,file) if (oldobject==objread):
with open("new.dat","rb") as file: pickle.dump(newobject,tfile)
pickle.dump(s3,file) while True: else:
try: pickle.dump(objread,tfile)
str=pickle.load(file) except EOFError:
break
print(str) tfile.close()
except EOFError: os.remove("new.dat")
KAPIL SEHGAL break os.rename("temp.dat","new.dat")
Binary file programs
write a program to read a Binary file “new.dat” delete the specific oBject
Delete
create import pickle
record=[]
import pickle t=(50,60,70)
with open("new.dat","wb") as file: with open("new.dat","rb+") as file:
s1="This is Vidisha" while True:
try:
s2="This is Jhansi" str=pickle.load(file)
s3="This is Ujjain" record.append(str)
s4=[10,20,30,"Ram","Krishna"] read except EOFError:
break
s5=(50,60,70)
import pickle count=-1
s6={"Name":"Ram","Age":25} for i in record:
with open("new.dat","rb") as file:
pickle.dump(s1,file) count=count+1
while True: if (i==t):
pickle.dump(s2,file)
try: break
pickle.dump(s3,file) del record[count]
str=pickle.load(file)
pickle.dump(s4,file) file.seek(0)
print(str) for i in record:
pickle.dump(s5,file)
except EOFError: pickle.dump(i,file)
pickle.dump(s6,file)
KAPIL SEHGAL break file.truncate()
Binary file programs
write a program to read a Binary file “new.dat” delete the specific oBject
Delete
create
import pickle
import pickle import os
with open("new.dat","wb") as file: oldobject="This is Jhansi"
s1="This is Vidisha" tfile=open("temp.dat","wb")
with open("new.dat","rb") as file:
s2="This is Jhansi"
read while True:
s3="This is Ujjain" try:
pickle.dump(s1,file) import pickle objread=pickle.load(file)
pickle.dump(s2,file) if (oldobject!=objread):
with open("new.dat","rb") as file: pickle.dump(objread,tfile)
pickle.dump(s3,file) while True: except EOFError:
try: break
str=pickle.load(file) tfile.close()
print(str) os.remove("new.dat")
except EOFError: os.rename("temp.dat","new.dat")
KAPIL SEHGAL break
c.s.v. file
A CSV is a comma-separated values file, which allows data to be saved in a tabular format. A CSV
file is a human readable text file where each line has a number of fields, separated by commas or some
other delimiter. The CSV file is opened as a text file

Reading data from C.S.V. File Creating C.S.V. File

(1) Import csv (1) Import csv


(2) Get Data using Reader Method into object. (2) Get Data from keyboard or any other way
(3) Fetch data from object and display on the screen (3) Make a object to store data using writer()
method
Methods for reading a file (4) Store the object using writerow() and
Methods for Writing into file writerows() methods
(1) reader()
(2) DictReader() (1) writer() :
(2) writerow()
(3) writerows()
(4) DictWriter()
KAPIL SEHGAL (5) writeheader()
Methods of c.s.v. file
reader() method
 The csv.reader() is used to read the file, which returns an ittrable reader object.

object= csv.reader(fileobject[,delimiter]) # by default “,”


Let the file “firstcsv.txt” Read this csv file as a list Read this csv file as individual
Contains elements
import csv
Name,Age import csv
with open("firstcsv.csv","r") as file:
Sourabh,16 with open("firstcsv.csv","r") as file:
obj=csv.reader(file,delimiter=‟,‟)
Abhishek,17 obj=csv.reader(file)
for row in obj:
Krishna,12 for row in obj:
print(row)
Arnav,13 print(row[0],",",row[1])
Note:-
Elements of CSV file fetch in Output:- Output:-
['Name', 'Age'] Name , Age
form of list # here row is a type ['Sourabh', '16'] Sourabh , 16
of LIST & ['Abhishek', '17'] Abhishek , 17
Do not access directly object ['Krishna', '12'] Krishna , 12
KAPIL SEHGAL ['Arnav', '13'] Arnav , 13
Write a program to read a csv file and store data into separate list
Let the file “firstcsv.txt”
Contains import csv
listnm=[]
Name,Age listage=[]
Sourabh,16 with open("firstcsv.csv","r") as file:
Abhishek,17 obj=csv.reader(file,delimiter=',')
Krishna,12 for row in obj:
Arnav,13 listnm.append(row[0])
listage.append(row[1])
print(listnm)
print(listage)

Output:-

['Name', 'Sourabh', 'Abhishek', 'Krishna', 'Arnav']


['Age', '16', '17', '12', '13']
KAPIL SEHGAL
Methods of c.s.v. file
writer() method
To write to a 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 later be used to write
into CSV files using the writerow() function.

writerobject=csv.writer(fileobject)
writerrow() method
writerow() method will write object row into the csv file one by one.
writerobject.writerow(row-of-object)

writerrows() method
writerows() method will write entire data object in one go into the csv file.
writerobject.writerows(data-object)
KAPIL SEHGAL
Write a program to write data into csv file
Let the file “firstcsv.txt” Using writerow() Method
Contains import csv
Name,Age list=[["Name","Age"],["Sourabh",16],["Abhishek",17],["Krishna",12],["Arnav",13]]
Sourabh,16 with open("secondcsv.csv","w") as file:
Abhishek,17 obj=csv.writer(file)
Krishna,12 for row in list:
Arnav,13 obj.writerow(row)

Using writerows() Method

import csv
list=[["Name1","Age"],["Sourabh",16],["Abhishek",17],["Krishna",12],["Arnav",13]]
with open("secondcsv.csv","w") as file:
obj=csv.writer(file)
obj.writerows(list)
KAPIL SEHGAL
Methods of c.s.v. file
DictReader() method
The csv.DictReader class operates like a regular reader but maps the information read into a dictionary.
The keys for the dictionary can be passed in with the fieldnames parameter or inferred from the first
row of the CSV file.
DicReaderObject=csv.DictReader(fileobject [,fieldnames=filenamelist])

When CSV file contains heading When CSV file does not contains heading
import csv
import csv with open("secondcsv.csv","r") as file:
with open("secondcsv.csv","r") as file: colname=['Name','Age']
obj=csv.DictReader(file) obj=csv.DictReader(file,fieldnames=colname)
for row in obj: for row in obj:
print(row) print(row)
print(row["Name"],",",row["Age"]) print(row["Name"],",",row["Age"])

KAPIL SEHGAL
DictWriter() method Methods of c.s.v. file
csv.DictWriter writes the values from Python dictionaries into the CSV file.

DicWriterObject=csv.DictWriter(fileobject [,fieldnames=filenamelist])

writeheader() method
The writeheader() method writes the headers to the CSV file. For ex. object.writeheader()

import csv
with open("newcsv.csv","w") as file:
sdict={'Stname':'Krishna','Rollno':151}
colname=['Stname','Rollno']
cwriter=csv.DictWriter(file,fieldnames=colname)
cwriter.writeheader()
cwriter.writerow(sdict)
cwriter.writerow({'Stname':'Ram','Rollno':150})
KAPIL SEHGAL

You might also like