0% found this document useful (0 votes)
12 views12 pages

Python File Operations and Data Management

cs python programs class 12

Uploaded by

sri.pranathi
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)
12 views12 pages

Python File Operations and Data Management

cs python programs class 12

Uploaded by

sri.pranathi
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

# Program-05.

Read a text file line by line and display each word


seperated by a ‘#’.
file = open("C:\\Users\\vidhyaashram\\Desktop\\[Link]", 'r')
lines = [Link] ( )
print(lines)
for line in lines :
words = [Link]( )
print(words)
for word in words :
print(word+"#", end =" ")
[Link] ( )

['hello everyone\n']
['hello', 'everyone']
hello# everyone#

'''Program-06: 06 Read a text file and display the number the number
of vowels/consonants/
uppercase/lowercase characters in the file.'''

file = open ("C:\\Users\\vidhyaashram\\Desktop\\[Link]", 'r')


content = [Link]( )
print(content)

vowels = 0
consonants = 0
lowercase = 0
uppercase = 0

for ch in content :
if ([Link]()):
if ([Link]( )):
lowercase += 1
elif ([Link]()):
uppercase +=1
ch = ([Link] ( ))
if (ch in ['a', 'e', 'i', 'o', 'u']) :
vowels += 1
else :
consonants += 1
[Link] ( )

print ("Vowels are : ", vowels)


print ("Consonants are : ", consonants)
print ("Lowercase are : ", lowercase)
print ("Uppercase are : ", uppercase)

hello everyone

Vowels are : 6
Consonants are : 7
Lowercase are : 13
Uppercase are : 0

'''Program - 7 (a):Create a binary file with name and roll no. Search
for a given roll no. and display
the name, if not found display appropriate message.'''

import pickle
file = open ("[Link]", "wb")
dic = { }
n = int (input ("Enter number of students: ") )
for key in range (n):
roll_no = int (input ("Enter roll no") )
name = input ("Enter name: ")
dic [roll_no] = { }
dic [roll_no] ["name"] = name
print(dic)
[Link] (dic, file)
[Link] ( )

Enter number of students: 2


Enter roll no 1
Enter name: Koushik
Enter roll no 2
Enter name: Abhilash

{1: {'name': 'Koushik'}, 2: {'name': 'Abhilash'}}

'''Program-7 (b) :Read data from binary file '''

import pickle
#opening the dictionary using command line:
file = open ("[Link]", "rb")
d = pickle. load (file)
roll_no = int (input ("Enter roll no to search the students name :") )
for key in d :
if key == roll_no :
print ("The name of roll no" , key, "is", d[key])
if (roll_no not in d) :
print ("This roll no doesn’t exist")
break
file. close ( )

Enter roll no to search the students name : 1

The name of roll no 1 is {'name': 'Koushik'}

'''Program-8 (a):Create a binary file with roll. number, name and


marks. Input the roll no. and
update the marks.'''
import pickle
file = open ("[Link]", "wb+")
dic = { }
n = int (input ("Enter number of students : ") )
for key in range (n) :
roll_no = int (input ("Enter roll no") )
name = input ("Enter name : ")
marks = int (input ("Enter your marks : ") )
dic [roll_no] = { }
dic [roll_no] ["name"] = name
dic [roll_no] ["marks"] = marks
print(dic)
pickle. dump (dic, file)
file. close ( )

Enter number of students : 2


Enter roll no 1
Enter name : Koushik
Enter your marks : 34
Enter roll no 2
Enter name : Abhilash
Enter your marks : 32

{1: {'name': 'Koushik', 'marks': 34}, 2: {'name': 'Abhilash', 'marks':


32}}

'''Program-8(b):Read data from binary file'''

import pickle
file = open ("[Link]", "rb+")
d = [Link](file)
roll_no = int (input ("Enter roll no to update marks") )
for key in d :
if key == roll_no:
m = int (input ("Enter the marks : ") )
d [roll_no] ["marks"] = m
print (d)
if roll_no not in d :
print ("roll no doesn’t exist")
break
[Link](d,file)
[Link] ( )

Enter roll no to update marks 1


Enter the marks : 56

{1: {'name': 'Koushik', 'marks': 56}, 2: {'name': 'Abhilash', 'marks':


32}}
'''Program - [Link] all the lines that contain the character ‘a’ in
a file and write it to another
file.'''
file = open ("C:\\Users\\vidhyaashram\\Desktop\\[Link]","r")
lines = [Link]( )
print(lines)
[Link]( )
file1 = open ("C:\\Users\\vidhyaashram\\Desktop\\[Link]",'w')
file2 = open ("C:\\Users\\vidhyaashram\\Desktop\\[Link]",'w')
for line in lines:
if 'a' in line or 'A' in line :
[Link](line)
else :
[Link](line)
print ("All lines that contains a char has been removed from
[Link]")
print ("All lines that contains a char has been saved in [Link]")
[Link] ( )
[Link] ( )

['kiwi\n', 'Apple\n', 'Banana\n', 'Orange\n']


All lines that contains a char has been removed from [Link]
All lines that contains a char has been saved in [Link]

'''Program - 10:Write a code for a random number generator that


generates random numbers
from 1 - 6 (Similar to a dice)'''

import random
while True :
choice = input ("Enter r to roll dice or press any other key to
quit")
if choice !='r':
break
n=[Link](1,6)
print(n)

Enter r to roll dice or press any other key to quit r

Enter r to roll dice or press any other key to quit 6

'''Program - 11:Take a sample of 10 phishing emails (or any text file)


and find the most commonly
occurring word'''

file = open ("C:\\Users\\vidhyaashram\\Desktop\\[Link]", 'r')


content=[Link]()
max=0
max_occuring_word=""
occurance_dict={}
words=[Link]()
for word in words:
count=[Link](word)
occurance_dict.update({word:count})
if(count>max):
max=count
max_occuring_word=word
print("most occuring word is:",max_occuring_word)
print("number of times it occurs:", max)
print("other words frequency:")
print(occurance_dict)

most occuring word is: hi


number of times it occurs: 2
other words frequency:
{'hello': 1, 'everyone': 1, 'hi': 2}

'''Program-12:Write a python program to implement a stack using a list


data structure'''

stack = []

# append() function to push


# element in the stack
[Link]('a')
[Link]('b')
[Link]('c')

print('Initial stack')
print(stack)
# pop() function to pop
# element from stack in
# LIFO order
print('\nElements popped from stack:')
print([Link]())
print([Link]())
print([Link]())

print('\nStack after elements are popped:')


print(stack)

Initial stack
['a', 'b', 'c']

Elements popped from stack:


c
b
a
Stack after elements are popped:
[]

'''Program-13 Write a python program to demonstrate .csv file'''

import csv
fh=open("[Link]","w")
stuwriter=[Link](fh)
[Link](["rollno","name","marks"])
for i in range(2):
print("student record", (i+1))
rollno=int(input ("enter rollno:"))
name=input("Enter the name:")
marks=float(input("enter marks"))
stu_rec=[rollno, name, marks]
[Link](stu_rec)
[Link]()

student record 1

enter rollno: 1
Enter the name: Koushik
enter marks 34

student record 2

enter rollno: 2
Enter the name: Abhilash
enter marks 35

'''program - 14:Create a CSV file by entering user-id and password,


read and search the password
for given user id'''

import csv
#user -id and password list
List=[["user1", "password1"],
["user2", "password2"],
["user3", "password3"],
["user4", "password4"],
["user5", "password5"]]

#opening the file to write the records


f1=open("[Link]","w",newline="\n")
# Here, you create a CSV writer object called writer associated with
the file f1.
writer=[Link](f1)
[Link](List)
[Link]()
#opening the file to read the records
f2=open("[Link]","r")
rows=[Link](f2)
userId=input("Enter the user-id:" )
flag = True
for record in rows:
if record[0]== userId:
print("The password is:",record[1])
flag= False
break
if flag:
print("User-id not found")

Enter the user-id:user8


User-id not found

''' Program-21:Write a Program to implement the Stack without using


pre defined Function'''

def isEmpty (stk) :


if stk == []:
return True
else :
return False

def Push (stk, item) :


[Link](item)
top = len(stk) - 1 # imagine [Link] element that i have in stack 5
then 5-1= 4

def Pop(stk) :
if isEmpty(stk) :
return "Underflow"
else :
item = [Link]()
if len(stk) == 0:
top = None
else:
top = len(stk) - 1
return item

def Peek(stk):
if isEmpty(stk):
return "UnderFlow"
else:
top=len(stk)-1
return stk[top]

def Display(stk):
if isEmpty(stk):
print("stack empty")
else :
top =len(stk)-1
print(stk[top],"<-top")
for a in range(top-1,-1,-1):
print(stk[a])

#_main_
Stack=[]
top=None
while True :
print("STACK OPERATIONS")
print("[Link]")
print("[Link]")
print("[Link]")
print("[Link] Stack")
print("[Link]")
ch=int(input("Enter your choice(1-5):"))
if ch==1:
item = int(input("Enter item:"))
Push(Stack, item)
elif ch==2:
item = Pop(Stack)
if item =='underflow':
print("Underflow!stack is empty!")
else:
print("popped item is",item)
elif ch==3:
item = Peek(Stack)
if item=='underflow':
print("Underflow! Stack is empty!")
else :
print('topmost item is',item)
elif ch==4:
Display(Stack)
elif ch==5:
break
else:
print("Invalid choice!")

STACK OPERATIONS
[Link]
[Link]
[Link]
[Link] Stack
[Link]
Enter your choice(1-5):1
Enter item:2
STACK OPERATIONS
[Link]
[Link]
[Link]
[Link] Stack
[Link]
Enter your choice(1-5):2
popped item is 2
STACK OPERATIONS
[Link]
[Link]
[Link]
[Link] Stack
[Link]
Enter your choice(1-5):1
Enter item:2
STACK OPERATIONS
[Link]
[Link]
[Link]
[Link] Stack
[Link]
Enter your choice(1-5):1
Enter item:3
STACK OPERATIONS
[Link]
[Link]
[Link]
[Link] Stack
[Link]
Enter your choice(1-5):3
topmost item is 3
STACK OPERATIONS
[Link]
[Link]
[Link]
[Link] Stack
[Link]
Enter your choice(1-5):4
3 <-top
2
STACK OPERATIONS
[Link]
[Link]
[Link]
[Link] Stack
[Link]
Enter your choice(1-5):5

'''[Link] a python interface program to demonstrate select


query.'''

import [Link] as sqltor


mycon= [Link](host =
"localhost",user="root",passwd="root",database="koushik")
if mycon.is_connected()== False:
print('Error')
cursor = [Link]()
[Link]("select * from student")
data=[Link]()
for row in data:
print(row)
[Link]()

('2', 'Venki', '33')


('3', 'Vani', '34')
('11', 'Rithes', '17')

'''[Link] a python interface program to demonstrate insert


query.'''

import [Link] as sqltor


mycon= [Link](host =
"localhost",user="root",passwd="root",database="koushik")
if mycon.is_connected()== False:
print('Error')
cursor = [Link]()
[Link]("insert into student values(11,'Rithes',17)")
[Link]()
print("One Record Inserted Successfully!!")
[Link]()

One Record Inserted Successfully!!

'''[Link] a python interface program to demonstrate delete


query.'''

import [Link] as sqltor


mycon= [Link](host =
"localhost",user="root",passwd="root",database="koushik")
if mycon.is_connected()== False:
print('Error')
cursor = [Link]()
[Link]("delete from student where name = 'ramu'")
[Link]()
print("Deleted Successfully")
[Link]()

Deleted Successfully

'''[Link] a python interface program to demonstrate update


query.'''

import [Link] as sqltor


mycon= [Link](host =
"localhost",user="root",passwd="root",database="koushik")
if mycon.is_connected()== False:
print('Error')
cursor = [Link]()
[Link]("update student set name='Venki' where sid=2")
[Link]()
print("Updated Successfully")
[Link]()

Updated Successfully

import [Link] as sqltor


mycon= [Link](host =
"localhost",user="root",passwd="root",database="koushik")

if mycon.is_connected()== False:
print('Error')

cursor = [Link]()
[Link]("select * from student")
data=[Link]()
count=[Link]
for row in data:
print(row)
[Link]()

mycon= [Link](host =
"localhost",user="root",passwd="root",database="koushik")
if mycon.is_connected()== False:
print('Error')

cursor = [Link]()
[Link]("insert into student values(10,'ramu',23)")
[Link]()
print("One Record Inserted Successfully!!")
[Link]()

mycon= [Link](host =
"localhost",user="root",passwd="root",database="koushik")
if mycon.is_connected()== False:
print('Error')

cursor = [Link]()
[Link]("delete from student where name = 'Abhi'")
[Link]()
print("Deleted Successfully")
[Link]()

mycon= [Link](host =
"localhost",user="root",passwd="root",database="koushik")
if mycon.is_connected()== False:
print('Error')

cursor = [Link]()
[Link]("update student set name='Vani' where sid=3")
[Link]()
print("Updated Successfully")
[Link]()

('2', 'Ravi', '33')


('3', 'Vani', '34')
('110', 'ramu', '23')
('10', 'ramu', '23')
('10', 'ramu', '23')
('10', 'ramu', '23')
('10', 'ramu', '23')
('10', 'ramu', '23')
One Record Inserted Successfully!!
Deleted Successfully
Updated Successfully

Common questions

Powered by AI

The program loads student data from a binary file into a dictionary and searches for the specified roll number. If found, it updates the marks for that roll number using input from the user, writes the updated data back to the file using pickle.dump(), and informs if the roll number does not exist .

The stack is implemented as a list where elements are appended with the append() method to push and are removed using the pop() method to simulate LIFO behavior. Custom functions for checking emptiness, pushing, popping, peeking, and displaying are defined, manually managing the stack size and top element .

The program uses Python's random module to generate a random integer between 1 and 6, simulating a dice roll, and provides continuous rolling until the user decides to quit by entering a different key .

The program establishes a connection with a MySQL database using mysql.connector, executing select, insert, and delete SQL commands through the cursor object. It selects all records, inserts new records with hardcoded values, and deletes records based on specific criteria, demonstrating CRUD operations .

The program opens a text file and reads it line by line. For each line, it splits the line into words using the split() function, iterating over each word to print them followed by a '#' symbol using the end parameter in print .

The program writes user-id and password pairs into a CSV file, which it later reads. During reading, it searches through records for a user-provided ID, displaying the corresponding password if found, or a not-found message if not .

The program takes input for multiple students, creating a dictionary with roll numbers as keys and corresponding names as values, which it writes to a binary file using pickle's dump(). For retrieval, it opens the binary file to load the dictionary with pickle's load(). It then searches for a user-provided roll number, displaying the name if found, or a not-found message otherwise .

The program reads lines from a text file, checks each line for the presence of 'a' or 'A', and writes lines that contain 'a' to one file while writing others to another file. This results in the separation of lines based on whether they contain the character 'a' .

The program creates a dictionary to count the occurrences of each word in the text. It splits the text into words and checks their frequency, updating the dictionary values accordingly. The most occurring word is determined by iterating over these counts and storing the word with the highest count value .

The program reads the content of the file and iterates through each character. It checks whether a character is an alphabet using isalpha(), then determines if it's lowercase or uppercase using islower() or isupper(). A lowercase representation of the character is checked against a list of vowels to count them; otherwise, it is counted as a consonant .

You might also like