Term 1 CS Practical File 2021-22
Term 1 CS Practical File 2021-22
CBSE
Logo
School Name
Address
[Name of Student]
supervision.
13 Read a CSV file students.csv and print them with tab delimiter. Ignore first
row header to print in tabular form.
14 Write records of customer into result.csv. The fields are as following:
Field 1 Data Type
StudentID Integer
StudentName String
Score Integer
15 Count the number of records and column names present in the CSV file.
Concepts used:
1. Skip first row using next() method
2. line_num properties used to count the no. of rows
2. Write a python program to accept username "Admin" as default argument and password 123
entered by user to allow login into the system.
def user_pass(password,username="Admin"):
if password=='123':
print("You have logged into system")
else:
print("Password is incorrect!!!!!!")
password=input("Enter the password:")
user_pass(password)
3. Write a python program to demonstrate the concept of variable length argument to calculate
product and power of the first 10 numbers.
def sum10(*n):
total=0
for i in n:
total=total + i
print("Sum of first 10 Numbers:",total)
sum10(1,2,3,4,5,6,7,8,9,10)
def product10(*n):
pr=1
for i in n:
pr=pr * i
print("Product of first 10 Numbers:",pr)
product10(1,2,3,4,5,6,7,8,9,10)
def program4():
f = open("intro.txt","w")
text=input("Enter the text:")
f.write(text)
f.close()
program4()
Input:
5. Write a program to count a total number of lines and count the total number of lines starting
with 'A', 'B', and 'C' from the file myfile.txt.
def program5():
with open("E:\\MyFile.txt","r") as f1:
data=f1.readlines()
cnt_lines=0
cnt_A=0
cnt_B=0
cnt_C=0
for lines in data:
cnt_lines+=1
if lines[0]=='A':
cnt_A+=1
if lines[0]=='B':
cnt_B+=1
if lines[0]=='C':
cnt_C+=1
6. Write a programto replace all spaces from text with - (dash) from the file intro.txt.
def program6():
cnt = 0
with open("intro.txt","r") as f1:
data = f1.read()
data=data.replace(' ','-')
with open("intro.txt","w") as f1:
f1.write(data)
with open("intro.txt","r") as f1:
print(f1.read())
program6()
7. Write a program to know the cursor position and print the text according to below-given
specifications:
a. Print the initial position
b. Move the cursor to 4th position
c. Display next 5 characters
d. Move the cursor to the next 10 characters
e. Print the current cursor position
f. Print next 10 characters from the current cursor position
8. Create a binary file client.dat to hold records like ClientID, Client name, and Address using the
dictionary. Write functions to write data, read them, and print on the screen.
import pickle
rec={}
def file_create():
f=open("client.dat","wb")
cno = int(input("Enter Client ID:"))
cname = input("Enter Client Name:")
address = input("Enter Address:")
rec={cno:[cname,address]}
pickle.dump(rec,f)
def read_data():
f = open("client.dat","rb")
print("*"*78)
print("Data stored in File....")
rec=pickle.load(f)
for i in rec:
print(rec[i])
file_create()
read_data()
CS PRACTICAL RECORD FILE | Downloaded from www.tutorialaicsip.com | Page 10
9. Write a program to create a binary file sales.dat and write a menu driven program to do the
following:
1. Insert record
2. Search Record
3. Update Record
4. Display record
5. Exit
import pickle
import os
def main_menu():
print("1. Insert a record")
print("2. Search a record")
print("3. Update a record")
print("4. Display a record")
print("5. Delete a record")
print("6. Exit")
ch = int(input("Enter your choice:"))
if ch==1:
insert_rec()
elif ch==2:
search_rec()
elif ch==3:
update_rec()
elif ch==4:
display_rec()
elif ch==5:
delete_rec()
elif ch==6:
print("Have a nice day!")
else:
print("Invalid Choice.")
def insert_rec():
f = open("sales.dat","ab")
c = 'yes'
while True:
sales_id=int(input("Enter ID:"))
name=input("Enter Name:")
city=input("Enter City:")
def display_rec():
f = open("sales.dat","rb")
try:
while True:
d = pickle.load(f)
print(d)
except Exception:
f.close()
main_menu()
def search_rec():
f = open("sales.dat","rb")
s=int(input("Enter id to search:"))
f1 = 0
try:
while True:
d = pickle.load(f)
if d["SalesId"]==s:
f1=1
print(d)
break
except Exception:
f.close()
if f1==0:
print("Record not found...")
else:
print("Record found...")
main_menu()
def update_rec():
f1 = open("sales.dat","rb")
f2 = open("temp.dat","wb")
def delete_rec():
f1 = open("sales.dat","rb")
f2 = open("temp.dat","wb")
s=int(input("Enter id to delete:"))
try:
while True:
d = pickle.load(f1)
if d["SalesId"]!=s:
pickle.dump(d,f2)
except EOFError:
print("Record Deleted.")
f1.close()
f2.close()
os.remove("sales.dat")
os.rename("temp.dat","sales.dat")
main_menu()
main_menu()
12. Read a CSV file top5.csv and print the contents in a proper format. The data for top5.csv file are as
following:
SNo Batsman Team Runs Highest
1 K L Rahul KXI 670 132*
2 S Dhawan DC 618 106*
3 David Warner SRH 548 85*
4 Shreyas Iyer DC 519 88*
5 Ishan Kishan MI 516 99
from csv import reader
def pro1():
with open("e:\\top5.csv","r") as f:
d = reader(f)
data=list(d)
for i in data:
print(i)
pro1()
14. Write records of students into result.csv. The fields are as following:
Field 1 Data Type
StudentID Integer
StudentName String
Score Integer
from csv import writer
def pro14():
#Create Header First
f = open("result.csv","w",newline='\n')
dt = writer(f)
dt.writerow(['Student_ID','StudentName','Score'])
f.close()
#Insert Data
f = open("result.csv","a",newline='\n')
while True:
st_id= int(input("Enter Student ID:"))
st_name = input("Enter Student name:")
st_score = input("Enter score:")
dt = writer(f)
dt.writerow([st_id,st_name,st_score])
ch=input("Want to insert More records?(y or
Y):")
ch=ch.lower()
if ch !='y':
break
print("Record has been added.")
f.close()
CS PRACTICAL RECORD FILE | Downloaded from www.tutorialaicsip.com | Page 17
15. Count the number of records and column names present in the CSV file.
Concepts used:
1. Skip first row using next() method
2. line_num properties used to count the no. of rows
import csv
def pro15():
fields = []
rows = []
with open('students.csv', newline='') as f:
data = csv.reader(f)
# Following command skips the first row of CSV file
fields = next(data)
print('Field names are:')
for field in fields:
print(field, "\t")
print()
print("Data of CSV File:")
for i in data:
print('\t'.join(i))
print("\nTotal no. of rows: %d"%(data.line_num))
pro15()