Class 12 CS File Handling
Class 12 CS File Handling
NACHARAM
SUB: CLASS XII COMPUTER SCIENCE
SUB CODE: 083
FILE HANDLING
PRASAD N
PGT COMPUTER
SCIENCE
DATA FILES
THE DATA FILES ARE THE FILES THAT
STORES DATA PERTAINING TO A SPECIFIC
APPLICATION, FOR LATER USE.
2. BINARY FILES
n’)
Binary Files:
A BINARY FILE IS JUST A FILE THAT CONTAINS INFORMATION IN
THE SAME FORMAT IN WHICH THE INFORMATION IS HELD IN
MEMORY
▪ IN BINARY FILE THERE IS NO DELIMITER FOR A LINE
▪ BINARY FILES ARE FASTER AND EASIER TO READ AND WRITE
▪ BINARY FILES ARE THE BEST WAY TO STORE PROGRAM
INFORMATION
OPENING AND CLOSING FILES
Absolute path:
Relative path:
Opening Files:
⮚Python provides built-in functions to perform file manipulation like adding, deleting
and modifying
Note: i. f1=open(“c:\\temp\\sample.txt”,”r”).read()
print(f1)
ii. f1=open(r “c:\temp\data.txt”,”r”)
METHOD SYNTAX DESCRIPTION
Creating a file:
f1=open("Sample.txt","w")
f1.write("how are you")
f1.close()
Writing onto files:
f1=open(“sample.txt”,”w”
)
for i in range(5):
name=input(“enter ur
name”)
f1.write(name)
f1.close()
Example 1: Reading a file’s entire content:
myfile=open(“license.txt”,”r”)
str=myfile.read()
Example 2: Reading a file’s first 20 bytes and print it:
print(str)
myfile.close() myfile=open(“license.txt”,”r”)
str=myfile.read(20)
print(str)
myfile.close()
Example 3: Reading a file’s first 20 bytes and then reading some more bytes
from the last position read:
f1=open(“license.txt”,”r”)
r1=f1.read(20)
print(r1)
r2=f1.read(50)
print(r2)
f1.close()
Example 4: Reading file using readline()
f1=open(“LICENSE.txt”,”r”)
r1=f1.readline() Example 5: Reading file’s first 20 bytes using readline()
print(r1) f1=open(“LICENSE.txt”,”r”)
f1.close() r1=f1.readline(20)
print(r1)
f1.close()
Example 6: Reading a file’s first 3 lines – line by line
myfile=open(“license.txt”,”r”)
str=myfile.readline()
print(str,end=‘ ‘)
str=myfile.readline()
print(str,end=‘ ‘)
str=myfile.readline()
print(str,end=‘ ‘)
myfile.close()
Example 7: Reading file using readline()
f1=open(“LICENSE.txt”,”r”)
r1=f1.readline() Example 8: Reading a complete file line by line
print(r1)
f1=open(“LICENSE.txt”,”r”)
f1.close()
str=“ “
Example 9: Reading a complete file in a list While str:
str=f1.readline()
f1=open(“LICENSE.txt”,”r”)
print(str,end=‘ ‘)
r1=f1.readlines()
f1.close()
print(r1)
f1.close()
Activity 1 : Write python code to create a text file “test.txt” and enter 5 lines of text
into that file and display content of the file “test.txt”
Activity 3: Reading n bytes and then reading some more bytes from the last position
read
File Access Modes:
TEXT BINARY FILE DESCRIPTION NOTES
FILE MODE
MODE
‘r’ ‘rb’ Read only File must exist already, otherwise I/O error will raise
‘w’ ‘wb’ Write only If the file does not exist, file is created.
If the file exists, python will truncate existing data over write in
the file
‘r+’ ‘r+b’ or ‘rb+’ Read and write File must exists otherwise error is raised, both reading and
writing operations can take place
‘w+’ ‘w+b’ or ‘wb+’ Write and read File is created if does not exists
If the file exists, file is truncated ( past data is lost)
Both reading and writing operations can take place
‘a+’ ‘a+b’ or ‘ab+’ Write and read File is created if does not exists
If file exists, file’s existing data is retained, new data is
appended
def write(): Activity 1
f=open(r"C:\Users\IT Dpet\Desktop\FirstFile.txt","w")
for i in range(5):
n=input("enter a name\n")
f.write(n+'\n')
f.close()
def read():
f=open(r"C:\Users\IT Dpet\Desktop\FirstFile.txt","r")
for i in f:
print(i.strip())
f.close()
#write()
read()
def noc():
f=open(r"C:\Users\Admin\Desktop\test.txt","r")
f1=f.read()
print(len(f1))
f.close() Counting
def now(): number of
f=open(r"C:\Users\Admin\Desktop\test.txt","r") characters and
count=0 numbers of
for i in f: Words in a File
word=i.split()
print(word)
count=count+len(word)
print(count)
f.close()
noc()
now()
Example :
1. Write a program to display the size of the file in bytes
2. Write a program to print number of lines in the file
3. Display the size of a file after removing EOL characters,
leading and trailing white spaces and blank lines
Example : Write a program to display the size of the file in
bytes
f1=open(“LICENSE.txt”,”r”)
r1=f1.read()
size=len(r1)
Print(size,”bytes”) Example : Write a program to print number of lines
in the file
f1=open(“LICENSE.txt”,”r”)
r1=f1.readlines()
linec=len(r1)
Print(linec)
example: display the size of a file after removing EOL characters, leading and
trailing white spaces and blank lines.
myfile=open(“license.txt”,”r”)
str1=“ “
size=0
size1=0
while str1:
str1=myfile.readline()
size1=size1+len(str1)
size=size+len(str1.strip())
print(“size of file after removing all EOL characters & blank lines:”, size)
print(“ total size of the file “, size1)
myfile.close()
Note:
leading whitespaces.
a. if the file has been opened in append mode to retain old content
b. If the file has been opened in ‘r+’ or ‘a+’ modes to facilitate reading as well as writing
2. To create a new file or to write on an existing file after truncating/overwriting its old content
b. if the file has been open in ‘w+’ mode to facilitate writing as well as reading
Activity:
Test.txt","w")
x=1
while x==1:
f.write(d+'\n')
number to exit"))
f.close()
f=open(r"C:\Users\AKSHARA\Desktop\
Test.txt","w")
x=1
while x==1:
l=[]
rn=int(input("enter rollno"))
l.append(rn)
name=input("enter your name")
l.append(name)
f.writelines(str(l))
x=int(input("enter 1 to continue or other
number to exit"))
f.close()
1. Write a python program to read a file “ data.txt” and display
those lines whose length is more than 45 characters
f=open(r'C:\Users\Admin\Desktop\myfile.txt','r')
for i in f:
if len(i)>45:
print(i.strip())
Write a program to count number of lines which all are starting with
‘A’ or ‘a’
count = 0
f=open('license.txt','r')
for i in f:
if i.startswith('A') or i.startswith('a'):
count += 1
print(count)
1. Write a method in python to read content from a text file line by
line and display the same on the screen
# Open the file in read mode
f=open(r'license.txt', 'r')
# Read all lines from the file into a list
lines = f.readlines()
# Display each line
for line in lines:
print(line.strip())# Remove any trailing newline characters
1. Write a program to read lines from a text file and display the
lines which all are starting with an alphabet ‘A’
f=open('license.txt','r')
f1 = f.readlines()
for i in f1:
if i.startswith('A'):
print(i.strip())
Write a python program to replace the word by another word in a given file.
f=open(r'C:\Users\Admin\Desktop\myfile.txt','r')
content = f.read()
# Replace the old word with the new word
content = content.replace('first', 'ffiirrsstt')
f.close()
# Write the updated content back to the file
f1=open(r'C:\Users\Admin\Desktop\myfile.txt', 'w')
f1.write(content)
f1.close()
✔ Write a program that reads a text file and create another file that is identical except that every sequence of
consecutive white spaces is replaced by a single space
f1=open("C:\\Users\\AKSHARA\\Desktop\\Test.txt","r")
f2=open("C:\\Users\\AKSHARA\\Desktop\\Test1.txt","w")
s=" "
while s:
s=f1.readline()
s1=s.split()
print(s1)
for i in s1:
f2.write(i)
f2.write(" ")
f2.write("\n")
f1.close()
f2.close()
wap to count no.of uppercase character in a file
f=open("C:\\Users\\AKSHARA\\Desktop\\Test.txt","r")
count=0
s=f.read()
for i in s:
if i.isupper():
count+=1
f1=open('C:\\Users\\AKSHARA\\Desktop\\Test1.txt','r')
s=" "
count=0
while s:
s=f1.readline()
s1=s.split()
for i in s1:
i=i.lower()
if i=='to' or i=='the' or i=='to\n' or i=='the\n' or i=='to,' or i=='the,':
count+=1
print(count)
f1.close()
✔ Python program for counting number of lines in a text file
f1=open("C:\\Users\\AKSHARA\\Desktop\\Test1.txt","r")
count=0
# Reading from file
rec=f1.read()
clines= rec.split("\n")
for i in clines:
if i:
count += 1
print("number of lines in the file")
print(count)
f1=open("C:\\Users\\AKSHARA\\Desktop\\Test1.txt","r")
s=" "
c=0
while s:
s=f1.readline()
s1=s.split(' ')
for i in s1:
✔ Python program to count no.of ‘to’ words in a file if 'to' in i.lower():
c+=1
'''i=i.lower()
if i=='to' or i=='to\n' or i=='to,':
c+=1'''
print("number of 'to' in a file",c)
f1.close()
✔ Python program to print the longest line in a file
f1=open("C:\\Users\\AKSHARA\\Desktop\\Test1.txt","r")
s=f1.readline()
str=s
max=len(s)
while s:
s=f1.readline()
if len(s)>max:
str=s
max=len(s)
print(str)
f1.close()
✔ WAP to print the statistics of a given file like no.of lines, no.of empty lines, average characters per line,
average characters per empty lines
f1=open("C:\\Users\\AKSHARA\\Desktop\\Test.txt","r")
str=" "
line=0
empty=0
characters=0
str=f1.readlines()
print("no.of lines in a file", len(str))
for line in str:
characters=characters+len(line)
if line=='\n':
empty+=1
print('no.of empty lines',empty)
print("avg characters per line",characters/len(str))
print("avg characters per empty line", characters//empty)
f1.close()
Flush() function:
When you want to write onto a file using any of the write function, python holds everything to write in the file in
buffer
and pushes it onto actual file on storage device a later time.
If however you want to force python to write the content of buffer onto storage, we can use flush() function.
Ex:
f=open(“sample.txt”,”w+”)
f.write(“c program”)
f.write(“c++ program”)
f.write(“java program”)
f.flush()
S=‘ok’
f.write(“python program”)
f.write(“\n”)
f.flush()
f.close()
Note:
flush() function forces the writing of data on disc still pending in output buffer
STANDARD INPUT, OUTPUT AND
ERROR STREAMS
Standard input device (stdin) 🡪 reads from the keyboard
for errors
Example:
import sys
f=open("sample.txt","w")
sys.stdout.write("welcome")
DIVISION OF TWO NUMBERS
import sys
sys.stdout.write("enter first number")
a=int(sys.stdin.readline())
if b==0:
sys.stderr.write("cannot divide")
else:
sys.stdout.write("division possible")
print(a/b)
Reading data from the file with stdin, stdout, stderr
import sys
sys.stdout.write("enter file name")
file=sys.stdin.readline()
f=open(r"C:\Users\Admin\Desktop\myfile.txt","r")
while True:
ch=f.read(1)
if ch=='':
sys.stderr.write("End of File")
break
else:
print(ch,end='')
f.close()
Sample code:
import sys
f=open("sample.txt","r+")
x=f.readline()
sys.stdout.write("python")
m=sys.stdin.read()
f.write(m)
n=sys.stdin.readline()
f.write(n)
sys.stderr.write(“error , file not closed")
import sys
f=open("check.txt","r+")
x=f.readline()
sys.stdout.write("name: "+x)
m=sys.stdin.read()
sys.stdout.write(m)
y=sys.stdin.readline()
sys.stdout.write(y)
f.close()
import sys
f=open("check.txt","r+")
z=1
while z==1:
x=f.readline()
sys.stdout.write("name: "+x)
m=sys.stdin.read()
sys.stdout.write(m)
y=sys.stdin.readline()
sys.stdout.write(y)
z=input("press 1 to continue or other
number to exit")
sys.stderr.write("no error in the
program")
File Pointer and read function:
f=open(“file.txt”,”r”)
print(f.read(2))
print(f.read(3))
Open a file Using with:
with open("C:\\Users\\AKSHARA\\Desktop\\Test.txt","r") as f:
x=f.read(2)
print(x)
Note:
Open() function is used to open binary file
Eg: f=open(“sample.dat”, “rb)
tell()
? This method can be used to get the position of the file handle
(Or )
? This method returns an integer giving the current position of object in the file.
? Syntax: file_object.tell()
Example:
Example 1:
f=open("sample1.txt
","r")
print(f.read(2))
print(f.tell())
print(f.read(3))
print(f.tell())
w e l c o m e t o p y t h o N
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
seek ()
? Seek function is used to change the position of the file pointer to a given specific
position
(Or )
? Seek method is used to position the file object at particular place in the file
f=open("C:\\Users\\AKSHARA\\Desktop\\Test.txt", "r")
print(f.seek(1))
print(f.read(2))
print(f.tell())
print(f.seek(1))
print(f.read(2))
print(f.tell())
f = open("abc.txt", "r")
f.seek(15)
print("Cursor Position :",f.tell())
data = f.read()
print(data)
f = open("abc.txt", "rb")
f.seek(-10, 2)
print("Cursor Position :",f.tell())
data = f.read()
print(data)
f=open(r"C:\Users\Admin\Desktop\myfile.txt","rb")
print(f.read(1))
print(f.tell())
f.seek(-1,2)
print(f.read())
With statement
? With statement in python is used in exception handling to make the
code cleaner and much more readable.
? With statement implicitly closes the file and even if exception is
generated, it preserves the content of the file
? Syntax:
with open(‘path’,’mode’) as <file_handle>:
? Example:
with open(“sample.tx”,”w”) as f:
f.write()
Binary files: pickling and unpickling
Structure
(list, dictionary pickling Byte stream
etc)
Unpickling:
Structure
Byte stream
unpickling (list, dictionary
etc)
dump():
import pickle
f=open("C:\\Users\\AKSHARA\\Desktop\\Python Programs\\binarywrite.dat","rb")
lst=pickle.load(f)
print(lst)
(or)
f.close() f=open("test1.dat","
rb")
pickle.load(f)
print(l)
import pickle
f1=open("C:\\Users\\AKSHARA\\Desktop\\Test1.txt","wb")
l=[]
ch='y'
while ch=='y':
name=input("enter ur name")
rno=int(input("enter rollno")) load, dump
l.append([name,rno]) program
ch=input("do u want to continue: 'y', 'n' ")
pickle.dump(l,f1)
print("content added successfully")
f1.close()
✔ Write a program to display all the records in a file along with line/record number.
f1=open("C:\\Users\\AKSHARA\\Desktop\\Test.dat","rb")
count=0
rec=" "
while True:
rec=f1.readline()
if rec==" ":
break
count=count+1
print(count,rec,end=' ')
f1.close()
Try Except in Python:
import pickle
f=open("C:\\Users\\AKSHARA\\Desktop\\Test1.dat","wb")
num=[5,10,15,20,25]
num1=[15,20,40,60,90]
dict={1:'Pythn', 2: 'C++'}
pickle.dump(num,f)
pickle.dump(num1,f)
pickle.dump(dict,f)
f.close()
f=open("C:\\Users\\AKSHARA\\Desktop\\Test1.dat","rb")
try:
while True:
s=pickle.load(f)
print(s)
except EOFError:
print("End of File Reached")
f.close()
try:
try:
x=3+3
x=3+3
except:
except:
print("they did't add due to x
x=4+4
value",x)
finally:
else:
print("will print",x)
print("will produce output with
the x value",x)
try:
x=3+3
except:
try:
x=4+4
x=x+3
else:
except:
x=x+1
x=4+4
finally:
finally:
print("will print",x)
print("will print",x)
Program for write and read in a binary file
import pickle
def write():
f=open("Test1.dat","wb") def read():
l=[] f=open(“Test1.dat","rb")
ch='y' try:
while ch=='y': s=pickle.load(f)
rno=int(input("enter rollno")) print(s)
name=input("enter ur name") except EOFError:
marks=int(input("enter marks")) pirnt("Error")
l.append([rno,name,marks]) f1.close()
ch=input("do you want to enter more press y or n")
pickle.dump(l,f)
f.close()
Program for Searching element in a binary file
def search():
f=open("C:\\Users\\AKSHARA\\Desktop\\Python Programs\\Test1.dat","rb")
key=int(input("enter your search element rno"))
s=pickle.load(f)
found=0
for i in s:
if i[0]==key:
print("element found",i)
found=1
if found==0:
print("no record found")
f.close()
write()
read()
search()
Program for append data in a binary file
def app():
print("want to append data")
f=open("C:\\Users\\AKSHARA\\Desktop\\Python Programs\\Test1.dat","ab+")
l=[]
ch='y'
while ch=='y':
rno=int(input("enter rollno"))
def read():
name=input("enter ur name") f=open("Test1.dat","rb")
while True:
marks=int(input("enter marks"))
try:
l.append([rno,name,marks]) s=pickle.load(f)
for i in s:
ch=input("do you want to enter more press y or n")
print(i)
pickle.dump(l,f) except EOFError:
print("Error")
f.close()
break
f.close()
Program for update record in a binary file
def update():
f=open("C:\\Users\\AKSHARA\\Desktop\\Python Programs\\Test1.dat","rb+")
s=pickle.load(f)
rno=int(input("enter rollnumber for update record"))
found=0
for i in s:
if rno==i[0]:
print("current rno is",i[0])
i[0]=int(input("enter new number"))
found=1
break
if found==0:
print("record not found")
else:
f.seek(0)
pickle.dump(s,f)
f.close()
Program for delete record from a binary file
def Del():
f=open("Test1.dat","rb+")
s=pickle.load(f)
t=[]
found=0
a=int(input("enter the rno to be deleted"))
for i in s:
if i[0]==a:
Method - 1
found=1
else:
t.append(i)
if found==0:
print("record not found")
else:
f.seek(0)
pickle.dump(t,f)
f.close()
Program for delete record from a binary file
try:
while True:
s=pickle.load(f)
if s[0]!=rno: Method - 2
pickle.dump(s,f1)
except:
f1.close()
f.close()
os.remove(Test1.dat")
os.rename("MyTest.dat",“Test1.dat")
import pickle
ch='y'
while ch=='y':
l=[]
rno=int(input("enter rollno"))
try:
exists=0
f=open("C:\\Users\\AKSHARA\\Desktop\\Python Programs\\Test1.dat","wb+")
while True:
s=pickle.load(f)
if s[0]==rno:
print("rollno already exists")
Program for accepting
exists=1
break unique data from user
except EOFError: in a binary file
f.close()
if exists==0:
f=open("C:\\Users\\AKSHARA\\Desktop\\Python Programs\\Test1.dat","ab+")
l.append(rno)
name=input("enter ur name")
l.append(name)
marks=int(input("enter marks"))
l.append(marks)
pickle.dump(l,f)
ch=input("enter y to continue")
f.close()
import pickle
#f=open("C:\\Users\\AKSHARA\\Desktop\\Python Programs\\Test1.dat","rb")
l=[]
'''
ch='y'
l.append([rollno,name])
while ch=='y':
ch=input("do you want to continue
rollno=int(input("enter your rollno"))
press y or N")
name=input("enter your name")
pickle.dump(l,f)
try:
f.close()
f=open("C:\\Users\\AKSHARA\\Desktop\\Python Programs\\Test1.dat","rb")
check=0
f=open("C:\\Users\\AKSHARA\\
while True:
Desktop\\Python Programs\\
s=pickle.load(f)
Test1.dat","rb")
if s[0]==rollno:
try:
print("already exists")
while True:
check=1
s=pickle.load(f)
break
print(s)
except EOFError:
except EOFError:
f.close()
print("EOF")
if check==0:
f.close()'''
l.append(rollno)
l.append(name)
f=open("C:\\Users\\AKSHARA\\Desktop\\Python Programs\\Test1.dat","ab+")
pickle.dump(l,f)
ch=input("enter y to continue")
f.close()
import pickle name=input("enter ur name")
def search(): rno=int(input("enter rollno"))
f1=open("C:\\Users\\AKSHARA\\Desktop\\Test1.dat","rb") l.append([name,rno])
a=int(input("enter search no")) #pickle.dump(l,f1)
found=0 ch=input("do u want to continue: 'y', 'n' ")
try: pickle.dump(l,f1)
while True and found==0: print("content added successfully")
r=pickle.load(f1) f1.close()
if r[0]==a:
print("found") def read():
print(r) f1=open("C:\\Users\\AKSHARA\\Desktop\\Test1.dat","rb")
found=1 try:
except EOFError: while True:
print("end of file reached") l=pickle.load(f1)
f1.close() print(l)
def write(): except EOFError:
f1=open("C:\\Users\\AKSHARA\\Desktop\\Test1.dat","wb") f1.close()
l=[]
ch='y' write()
while ch=='y': read()
search()
read()
import pickle
ch='y'
if exists==0:
while ch=='y':
l.append(roll)
l=[]
f=open("C:\\Users\\AKSHARA\\Desktop\\Test1.dat","wb")
roll=int(input("enter rollno"))
name=input("enter your name")
try:
l.append(name)
exists=0
marks=[]
f=open("C:\\Users\\AKSHARA\\Desktop\\Test1.dat","rb")
for i in range(0,3):
while True:
x=float(input("enter marks"))
s=pickle.load(f)
marks.append(x)
if s[0]==roll:
l.append(marks)
print("roll number exists")
pickle.dump(l,f)
exists=1
ans=input("enter y to continue")
break
f.close()
except EOFError:
f.close()
Python - OS
Module
The OS module in Python provides functions for creating and removing a directory (folder),
fetching its contents, changing and identifying the current directory, etc.
def add_record():
try:#function definition
if os.path.isfile("stud"):
f=open("stud","ab")
else:
f=open("stud","wb")
roll=int(input("Enter roll no "))
name=input("Enter name ")
name=name.upper()
per=float(input("Enter per "))
rec=[roll,name,per]
pickle.dump(rec,f)
print("Record added in file")
except EOFError:
f.close()
add_record()
COMMA SEPARATED VALUES
CSV FILES
⮚ To share large amount of data through spreadsheets or
database.
⮚ A CSV file stores tabular data (numbers and text) in plain text
For working with CSV files in Python, there is an inbuilt module called
CSV. It is used to read and write tabular data in CSV format.
Features:
• Faster to handle
• Smaller in size
• Easy to generate and import onto a spreadsheet or database
• Human readable and easy to edit
• Simple to implement
Python CSV modules
f=open(“student.csv”,”w”)
(or)
f= open(“student.csv”,”r”)
Functions used to write csv file:
import csv
fields =['rno', 'name', 'classes', 'section']
rows=[['1','raj','12','A'],
['2', 'ram', '12', 'B']]
with open("std.csv",'w') as f1:
w=csv.writer(f1)
w.writerow(fields)
for i in rows:
w.writerow(i)
Writerows( ):
import csv
fields =['rno', 'name', 'classes', 'section']
rows=[['1','raj','12','A'],
['2', 'ram', '12', 'B']]
with open("std.csv",'w') as f1:
w=csv.writer(f1)
w.writerow(fields)
w.writerows(rows)
import csv
def write(): def read():
f=open(“mycsvfile.csv","w",newline='') f=open(“mycsvfile.csv","r")
w=csv.writer(f,delimiter='\t') r=csv.reader(f)
w.writerow(['RollNo','Name','Marks','Class']) for i in r:
while True: print(i)
r=int(input("rollno")) write()
n=input("enter name") read()
m=int(input("marks"))
c=input("enter class")
data=[r,n,m,c]
w.writerow(data)
ch=input("press Y to continue")
if ch in 'Nn':
break
f.close()
import csv
fields =['rno', 'name', 'classes', 'section']
rows=[]
ch='y'
while ch=='y':
name=input("enter your name")
rno=input("enter your rollno")
Class=input("enter your class")
section=input("enter your section")
rec=[name,rno,Class,section]
rows.append(rec)
ch=input("do you want to add more records y/N")
input: w.writerow(fields)
w.writerows(rows)
Read from CSV file:
• To read from CSV file we have to open file in “r” mode and create a
folder object for the file
import csv
with open("std.csv","r",newline='\r\n') as f:
r=csv.reader(f)
for i in r:
print(i)
print()
import csv
field=[]
row=[]
with open("std.csv","r",newline='\
r\n')as f:
r=csv.reader(f)
field=next(r)
for i in field:
print(i,end='\t')
print()
for row in r:
for i in row:
print(i)
print()
import csv
with open("std.csv","w") as f:
w=csv.writer(f)
w.writerow(['SNO','SNAME','SADD'])
ch='y'
while ch=='y':
sno=int(input("enter rno"))
sname=input('enter name')
sadd=input("enter address")
w.writerow([sno,sname,sadd])
ch=input("enter ur choice")
print("data added successfully")
with open("std.csv","r",newline='\r\n') as f:
r=csv.reader(f)
data=list(r)
for row in data:
for column in row:
print(column,'\t',end='')
print()
# Program for printing number of records
with open("std.csv","r",newline='\r\n') as f:
r=csv.reader(f)
c=0
data=list(r)
for row in data:
c+=1
print(c-1)
# Program for printing number of records
import csv
def read():
with open("C:\\Users\\AKSHARA\\Desktop\\
Python Programs\\std.csv",'r') as f1:
row=csv.reader(f1)
c=0
for i in row:
c=c+1
print("no.of records are",c)
read()
# Program for printing number of records -
method 2
import csv
def read():
with open("C:\\Users\\AKSHARA\\Desktop\\
Python Programs\\std.csv",'r') as f1:
row=csv.reader(f1)
c=0
for i in row:
print(i)
print()
print("no.of records ",row.line_num)
Program to print the records in the form of comma separated
values, instead of lists.
with open("std.csv","r",newline='\
r\n') as f:
r=csv.reader(f)
c=0
data=list(r)
for row in data:
print(','.join(row))
# Program to search the record of a particular student
from CSV file on the basis of input name.
import csv
f=open(“std.csv”,”r”)
r=csv.reader(f)
name=input(“enter name to be searched”)
for row in r:
if row[0]==name:
print(row)
Practice Programs
Write a method COUNTLINES() in Python to read lines from text file ‘TESTFILE.TXT’ and display the lines which are not starting with any
vowel.
def COUNTLINES() :
lines = file.readlines()
count=0
for w in lines :
count = count + 1
print ("The number of lines not starting with any vowel: ",
count)
file.close()
Write a function ETCount() in Python, which should read each character of a text file “TESTFILE.TXT” and then
count and display the count of occurrence of alphabets E and T individually (including small cases e and t too).
def ETCount() :
lines = file.readlines()
countE=0
countT=0
for w in lines :
for ch in w:
if ch in 'Ee':
countE = countE + 1
if ch in 'Tt':
countT=countT + 1
file.close()
Rohit, a student of class 12th, is learning CSV File Module in Python.
During examination, he has been assigned an incomplete python code
(shown below) to create a CSV File 'Student.csv' (content shown below).
Help him in completing the code which creates the desired CSV File.
CSV File
1,AKSHAY,XII,A
2,ABHISHEK,XII,A
3,ARVIND,XII,A
4,RAVI,XII,A
5,ASHISH,XII,A
import_____ #Statement-1
data = []
data.append(header)
for i in range(5):
data.append(rec)
fh.close()
Amritya Seth is a programmer, who has recently been given a task to write a python code to
perform the following binary file operations with the help of two user defined
functions/modules: a. AddStudents() to create a binary file called STUDENT.DAT containing
student information – roll number, name and marks (out of 100) of each student. b.
GetStudents() to display the name and percentage of those students who have a percentage
greater than 75. In case there is no student having percentage > 75 the function displays an
appropriate message. The function should also display the average percent. He has
succeeded in writing partial code and has missed out certain statements, so he has left
certain queries in comment lines. You as an expert of Python have to provide the missing
statements and other related queries based on the following code of Amritya.