Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
13 views24 pages

Python File and SQL Operations

The document outlines various Python programming exercises, including reading and processing text files, managing binary files, implementing a stack, and performing SQL operations on a student database. Each exercise includes an aim, program code, and expected output. The exercises cover file manipulation, data searching, updating records, and basic SQL commands for database management.

Uploaded by

Sarveshanju
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views24 pages

Python File and SQL Operations

The document outlines various Python programming exercises, including reading and processing text files, managing binary files, implementing a stack, and performing SQL operations on a student database. Each exercise includes an aim, program code, and expected output. The exercises cover file manipulation, data searching, updating records, and basic SQL commands for database management.

Uploaded by

Sarveshanju
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

EX.

NO:1 READ A TEXT FILE LINE BY LINE AND DISPLAY EACH WORD SEPARATED BY ‘#’

AIM

To write a python program to read a text file line by line and display each word separated by a #.

PROGRAM

file=open("PRACTICAL1.TXT","r")

lines=file.readlines()

for line in lines:

words=line.split()

for word in words:

print(word+"#",end="")

print("")

file.close()
OUTPUT

SAMPLE TEXT FILE

PROGRAM OUTPUT
EX.NO:2 READ A TEXT FILE AND DISPLAY THE NUMBER OF
VOWELS/CONSONANTS/UPPERCASE/LOWERCASE CHARACTERS IN THE FILE

AIM

To write a python program to read a text file and display the number of vowels/ consonants/
uppercase/ lowercase characters in the file.

PROGRAM

file=open("PRACTICAL1.TXT","r")

content=file.read()

vowels=0

consonants=0

lower_case_letters=0

upper_case_letters=0

for ch in content:

if(ch.islower()):

lower_case_letters+=1

elif(ch.isupper()):

upper_case_letters+=1

ch=ch.lower()

if (ch in ['a','e','i','o','u']):

vowels+=1

elif(ch in ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']):

consonants+=1

file.close()

print("Vowels are :",vowels)

print("Consonants :",consonants)
print("Lower_case_letters :",lower_case_letters)

print("Upper_case_letters :",upper_case_letters)
OUTPUT

SAMPLE TEXT FILE

PROGRAM OUTPUT
EX.NO:3 SEARCHING DATA IN A BINARY FILE

AIM

To write a python program to create a binary file with name and roll number and to search for a given
roll number and display the name.

PROGRAM
“Create a binary file with name and roll number
import pickle
stud_data={}
list_of_students=[]
no_of_students=int(input("Enter no of Students:"))
for i in range(no_of_students):
stud_data["roll_no"]=int(input("Enter roll no:"))
stud_data["name"]=input("Enter name: ")
list_of_students.append(stud_data)
stud_data={}
file=open("C:\\Users\\dasam\\Desktop\\stud_data.dat","wb")
pickle.dump(list_of_students,file)
print("Data added successfully")
file.close()

“Search for a given roll number and display the name, if not found display appropriate message.”
import pickle
file=open("C:\\Users\\dasam\\Desktop\\stud_data.dat","rb")
list_of_students=pickle.load(file)
roll_no=int(input("Enter roll no.of student to search"))
found=False
for stud_data in list_of_students:
if(stud_data["roll_no"]==roll_no):
found=True
print(stud_data["name"],"found in file.")
if (found==False):
print("No student data found. please try again")

file.close()
OUTPUT
EX.NO:4 UPDATING DATA IN A BINARY FILE

AIM

To write a python program to create a binary file with roll number, name and marks and input a roll
number and update the marks.

PROGRAM

#Create a binary file with roll number, name and marks.


import pickle
student_data={}
no_of_students=int(input("Enter no..of Students to insert in file : "))
file=open("C:\\Users\\dasam\\Desktop\\student_data","wb")
for i in range(no_of_students):
student_data["RollNo"]=int(input("Enter roll no :"))
student_data["Name"]=input("Enter Student Name :")
student_data["Marks"]=float(input("Enter Students Marks :"))
pickle.dump(student_data,file)
student_data={}
file.close()
print("data inserted Successfully")

#Input a roll number and update the marks.


import pickle
student_data={}
found=False
roll_no=int(input("Enter the roll no to search :"))
file=open("C:\\Users\\dasam\\Desktop\\student_data","rb+")
try:
while True:
pos=file.tell()
student_data=pickle.load(file)
if(student_data["RollNo"]==roll_no):
student_data["Marks"]=float(input("Enter marks to update"))
file.seek(pos)
pickle.dump(student_data,file)
found=True
except EOFError:
if(found==False):
print("Roll no not found.please try again")
else:
print("Students marks updated Successfully")
file.close()

# print the updated data


import pickle
student_data={}
file=open("C:\\Users\\dasam\\Desktop\\student_data","rb")
try:
while True:
student_data=pickle.load(file)
print(student_data)
except EOFError:
file.close()
OUTPUT
EX.NO:5 FILE OPERATIONS

AIM

To write a python program to remove all the lines that contain the character `a' in a file and write it to
another file.

PROGRAM

file=open("C:\\Users\\dasam\\Desktop\\format.txt","r")
lines=file.readlines()
file.close()

file=open("C:\\Users\\dasam\\Desktop\\format.txt","w")
file1=open("C:\\Users\\dasam\\Desktop\\second.txt","w")
for line in lines:
if 'a' in line or 'A' in line:
file1.write(line)
else:
file.write(line)
print("All lines that contains 'a' character has been removed in format.txt file")
print("All lines that contains 'a' character has been saved in second.txt file")
file.close()
file1.close()
OUTPUT
EX.NO:6 RANDOM NUMBER GENERATOR

AIM:

To write a random number generator that generates random numbers between 1 and 6.

PROGRAM:

import random
while(True):
choice=input("Enter (r) for roll dice or press any other key to quit")
if(choice!="r"):
break
n=random.randint(1,6)
print(n)
OUTPUT
EX.NO:7 IMPLEMENTATION OF STACK USING LIST

AIM:

To write a Python program to implement a stack using a list data-structure.

PROGRAM:

def push():

a=int(input("Enter the element which you want to push:"))

stack.append(a)

return a

def pop():

if stack==[]:

print("Stack empty....Underflow case....can not delete the element...")

else:

print("deleted element is :",stack.pop())

def display():

if stack==[]:

print("Stack empty....no elements in stack..")

else:

for i in range(len(stack)-1,-1,-1):

print(stack[i])

stack=[ ]

print("STACK OPERATIONS")

print("***********************")

choice="y"
while choice=="y":

print("1.PUSH")

print("2.POP")

print("3.DISPLAY ELEMENTS OF STACK")

print("************************************")

c=int(input("Enter your choice : "))

if c==1:

push()

elif c==2:

pop()

elif c==3:

display()

else:

print("wrong input:")

choice=input("Do you want to continue or not?(y/n) : ")


OUTPUT
8) Create a student table with student_id, name and marks as attributes
where student_id is primary key SQL>CREATE TABLE STUDENT

SQL> CREATE TABLE students

ID int primary key, NAME varchar(20) ,

GENDER varchar(1),SECTION varchar(1),

STREAM varchar(10),MARKS int

);
9) Insert the details of a new student in the above table

SQL>INSERT INTO students VALUES (1, 'Rohit','M','C','CEC','74');

SQL>INSERT INTO students VALUES (2, 'Janani','F','A','MPC','85');

SQL>INSERT INTO students VALUES (3, 'Ronit','M','B','BiPC','96');

SQL>INSERT INTO students VALUES (4, 'Akshara','F','B','BiPC','98');

SQL>INSERT INTO students VALUES (5, 'Karthik','M','D','MEC','81');

SQL>INSERT INTO students VALUES (6, 'Prakash','M','C','CEC','91');

SQL>INSERT INTO students VALUES (7, 'Janaki','F','E','HEC','85');

SQL>INSERT INTO students VALUES (8, 'Abhay','M','A','MPC','56');

SQL>INSERT INTO students VALUES (9, 'Akhil','M','D', 'MEC','72');

SQL>INSERT INTO students VALUES (10, 'Vishal','M', 'E','HEC','69');

SQL>INSERT INTO students VALUES (11, 'Shrilata','F', 'C','CEC','34');


10) Delete the details of a student in the above table;

SQL>SELECT * FROM students;

SQL>DELETE FROM students WHERE ID=11;

11) Use the select command to get the details of the students with marks more than 80

SQL> SELECT * FROM STUDENT WHERE MARKS>80;


12) Find the min, max, sum, and average of the marks in a student marks table

SQL>SELECT min(MARKS),max(MARKS),sum(MARKS) FROM students;

13) Write a SQL query to order the (student ID, marks) table in descending order of the
marks

SQL>SELECT * FROM students ORDER BY MARKS desc;


14) Find the total number of customers from each country in the table (cus
tomer ID, customer Name, country) using group by

SQL>CREATE TABLE CONSUMER

(Customer_ID int ,

Customer_Name VARCHAR(15),

country VARCHAR(15)

);

SQL>insert into CONSUMER values(1,'Khusha','India');

SQL>insert into CONSUMER values(2,'Kajal','Nepal') ;

SQL>insert into CONSUMER values(3,'Diya','India');

SQL>insert into CONSUMER values(4,'Rahul','Nepal');

SQL>insert into CONSUMER values(5,'Neha','Sri Lanka');

SQL>insert into CONSUMER values(6,'Dhruv','Sri Lanka');

SQL>SELECT * FROM CONSUMER;

SQL>SELECT country, count(*) from CONSUMER GROUP BY country;

You might also like