0% found this document useful (0 votes)
77 views

Python Programming and SQL

The document discusses several Python programming concepts including: 1. Reading a text file line by line and counting the number of vowels, consonants, uppercase letters, lowercase letters, digits, and other characters. 2. Creating a binary file to store student records with roll number and name, searching the file to retrieve a name based on roll number. 3. Updating an existing binary file by allowing the user to input a new roll number and modifying details like name, percentage, and remarks in the file. 4. Removing all lines containing a specific character from one file and writing the output to a new file.

Uploaded by

BADLA FF
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)
77 views

Python Programming and SQL

The document discusses several Python programming concepts including: 1. Reading a text file line by line and counting the number of vowels, consonants, uppercase letters, lowercase letters, digits, and other characters. 2. Creating a binary file to store student records with roll number and name, searching the file to retrieve a name based on roll number. 3. Updating an existing binary file by allowing the user to input a new roll number and modifying details like name, percentage, and remarks in the file. 4. Removing all lines containing a specific character from one file and writing the output to a new file.

Uploaded by

BADLA FF
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/ 5

count_vow = 0

Python Programming count_con = 0


count_low = 0
count_up = 0
count_digit = 0
1 .Read a text file line by line and display each count_other = 0
word separated by a #. print(line)
for ch in line:
 
     if ch.isupper():
filein = open("file.txt",'r')           count_up +=1
line =" "      if ch.islower():
while line:           count_low += 1
     line = filein.readline()      if ch in 'aeiouAEIOU':
          count_vow += 1
     for w in line:      if ch.isalpha():
          if w == ' ':           count_con += 1
               print('#',end = '')      if ch.isdigit():
          else:           count_digit += 1
               print(w,end = '')      if not ch.isalnum() and ch !=' ' and ch !='\n':
filein.close()           count_other += 1
          
print("Digits",count_digit)          
'''
print("Vowels: ",count_vow)
#-------------OR------------------
print("Consonants: ",count_con-count_vow)
filein = open("file.txt",'r') print("Upper Case: ",count_up)
for  line in filein: print("Lower Case: ",count_low)
     word= line .split() print("other than letters and digit:
     for w in word: ",count_other)
          print(w + '#',end ='')
filein.close()
     print()
filein.close()

'''
 
3.Create a binary file with the name and roll
2. Read a text file and display the number of number. Search for a given roll number and
vowels/ consonants/ uppercase/ lowercase display the name, if not found display
characters and other than character and digit appropriate message.
in the file.

import pickle
filein = open("file.txt",'r')
#creating the file and writing the data
line = filein.read()
f=open("records.dat", "wb")
srecord={"SROLL":sroll,"SNAME":sname,"SPERC
pickle.dump(["Wakil", 1], f)
":sperc,
pickle.dump(["Tanish", 2], f)
"SREMARKS":sremark}
pickle.dump(["Priyashi", 3], f)
pickle.dump(srecord,Myfile)
pickle.dump(["Kanupriya", 4], f)

pickle.dump(["Aaheli", 5], f)
def Readrecord():
f.close()
with open ('StudentRecord.dat','rb') as
#opeining the file to read contents Myfile:

f=open("records.dat", "rb") print("\n-------DISPALY STUDENTS


DETAILS--------")
n=int(input("Enter the Roll Number: "))
print("\nRoll No.",' ','Name','\t',end='')
flag = False
print('Percetage',' ','Remarks')
while True:
while True:
try:
try:
x=pickle.load(f)
rec=pickle.load(Myfile)
if x[1]==n:
print(' ',rec['SROLL'],'\t
print("Name: ", x[0]) ' ,rec['SNAME'],'\t ',end='')
flag = True print(rec['SPERC'],'\t
except EOFError: ',rec['SREMARKS'])

break except EOFError:

if flag==False: break

print("This Roll Number does not exist") def Input():

n=int(input("How many records you want to


create :"))
4. Create a binary file with roll number, name
and marks. Input a roll number and update for ctr in range(n):
details. sroll=int(input("Enter Roll No: "))

sname=input("Enter Name: ")

sperc=float(input("Enter Percentage: "))


def Writerecord(sroll,sname,sperc,sremark): sremark=input("Enter Remark: ")
with open ('StudentRecord.dat','ab') as Writerecord(sroll,sname,sperc,sremark)
Myfile:
with open ('StudentRecord.dat','wb') as
Myfile:

for j in newRecord:
def Modify(roll):
pickle.dump(j,Myfile)
with open ('StudentRecord.dat','rb') as
Myfile:

newRecord=[]

while True: def main():

try:

rec=pickle.load(Myfile) while True:

newRecord.append(rec) print('\nYour Choices are: ')

except EOFError: print('1.Insert Records')

break print('2.Dispaly Records')

found=1 print('3.Update Records')

for i in range(len(newRecord)): print('0.Exit (Enter 0 to exit)')

if newRecord[i]['SROLL']==roll: ch=int(input('Enter Your Choice: '))

name=input("Enter Name: ") if ch==1:

perc=float(input("Enter Percentage: ")) Input()

remark=input("Enter Remark: ") elif ch==2:

Readrecord()

newRecord[i]['SNAME']=name elif ch==3:

newRecord[i]['SPERC']=perc r =int(input("Enter a Rollno to be update:


"))
newRecord[i]['SREMARKS']=remark
Modify(r)
found =1
else:
else:
break
found=0
main()

if found==0:
5. Remove all the lines that contain the
character `a' in a file and write it to another
print("Record not found") file
#Python program to

# demonstrate stack implementation

# using list

f1 = open("file.txt")

f2 = open("copyfile.txt","w") stack = []

for line in f1:

if 'a' not in line: # append() function to push

f2.write(line) # element in the stack

print('## File Copied Successfully! ##') stack.append('a')

f1.close() stack.append('b')

f2.close() stack.append('c')

f2 = open("copyFile.txt","r") print('Initial stack')

print(f2.read()) print(stack)

6. Write a random number generator that


generates random numbers between 1 and 6
# pop() function to pop
(simulates a dice).
# element from stack in

# LIFO order

print('\nElements popped from stack:')


import random
min = 1 print(stack.pop())
max = 6
roll_again = "y" print(stack.pop())
while roll_again == "y" or print(stack.pop())
roll_again == "Y":
print("Rolling the
dice...")
val = random.randint (min, print('\nStack after elements are popped:')
max)
print(stack)
print("You get... :", val)
roll_again = input("Roll
the dice again? (y/n)...")
# uncommenting print(stack.pop())

# will cause an IndexError


7.Write a Python program to implement a
stack using list # as the stack is now empty
8. Create a CSV file by entering user-id and break
password, read and search the password for
given user id

import csv

with open("user_info.csv", "w") as


obj:

fileobj = csv.writer(obj)

fileobj.writerow(["User Id",
"password"])

while(True):

user_id = input("enter id:


")

password = input("enter
password: ")

record = [user_id, password]

fileobj.writerow(record)

x = input("press Y/y to
continue and N/n to terminate the
program\n")

if x in "Nn":

break

elif x in "Yy":

continue

with open("user_info.csv", "r") as


obj2:

fileobj2 = csv.reader(obj2)

given = input("enter the user id


to be searched\n")

for i in fileobj2:

next(fileobj2)

# print(i,given)

if i[0] == given:

print(i[1])

You might also like