CSpractical File Copy 2
CSpractical File Copy 2
PYTHON PROGRAMS
SNO. PYTHON PROGRAM REMARK
1. Read a text file line by line and display each word separated by #.
3. Remove all the lines that contain the character ‘a’ in a file and
write it to another file.
4. Create a Binary file with name and roll number. Search for a given
roll number and display the name, if not found display appropriate
message.
6. Create a binary file with roll number , name and marks. Input a roll
number and update the marks .
11. Write a user defined function CreateFile() to input data for record
and add to ‘Book.dat’
12. Program to input a string and count the number of uppercase and
lowercase letters.
13. Program to find maximum , minimum , and mean value from the
List
14. Write a Python function to sum all the items in a list .
15. Python program to search record for given students name from
csv file .
PYTHON
PROGRAMS
.
Q1.) Read a text file line by line and
display each word separated by #.
CODING :
def wordseperated():
f=open("xyz.txt","r")
lines=f.readlines()
for line in lines:
words=line.split()
for word in words:
print(word+'#',end='')
print()
wordseperated()
OUTPUT :
Q2.) Read a text file and display the number
of vowels/consonants/uppercase/lowercase
characters in the file.
CODING :
def diff():
f=open("xyz.txt",'r')
v=c=u=l=0
data= f.read()
for i in data:
if i.isupper():
u+=1
if i.islower():
l+=1
if i.lower() in 'aeiou' :
v+=1
else:
c+=1
print("Vowels=",v)
print("Consonents=",c)
print("upper case=",u)
print("lower case=",l)
diff()
OUTPUT :
Q3.) Remove all the lines that contain the
character ‘a’ in a file and write it to
another file.
CODING :
fn1= open("xyz.txt",'r')
fn2= open("anew.txt", 'w')
data1= fn1.readlines()
for line in data1:
if 'a' not in line:
fn2.write(line)
fn1.close()
fn2.close()
print("task accomplished")
OUTPUT:
Q4.) Create a Binary file with name and
roll number. Search for a given roll number
and display the name, if not found display
appropriate message.
CODING :
import pickle
stu= {}
fh1=open('sagar.dat',"ab+")
ans= 'y'
while ans=='y' :
stu['Rollno']= int(input("Enter Rollno :"))
stu['name']= input("Enter name of student:")
pickle.dump(stu,fh1)
ans= input("Do you want to enter more('y'/'n')...")
fh1.close()
#Part 2
key=int(input("Enter the roll no to be searched:"))
fh2=open("sagar.dat",'rb+')
found=False
try:
while True:
stu=pickle.load(fh2)
if stu["Rollno"]==key:
found=True
print("The SEarched ROlno is found:")
print(stu)
except EOFError:
if found==False:
print("Searching Completed")
else:
print("The Searched Roll No does not exist:")
fh2.close()
OUTPUT :
Q5.) Write a Random number generator
that generates random numbers between 1
and 6 (simulates a dice ).
CODING :
def random():
import random
s=random.randint(1,6)
return s
while True:
ch=int(input("Enter 1 to Roll the dice and any other key to
exit..."))
if ch==1:
print('Dice:',random())
else:
print("Game over ")
break
OUTPUT:
Q6.) Create a binary file with roll number ,
name and marks. Input a roll number and
update the marks .
CODING :
import pickle
stu={}
fh1=open("Student.dat",'ab+')
ans=input("Enter the data to file (y/n)...")
while ans=='y' or ans=='Y':
stu['Rollno']=int(input("Enter Roll Number:"))
stu['Name']=input("Enter Name:")
stu['Marks']=int(input("Enter the marks :"))
pickle.dump(stu,fh1)
ans= input("Want to enter more?(y/n)...")
fh1.close()
print()
#Part 2
key=int(input("Enter the Roll Number whose marks is to be updated :"))
fh2=open("Student.dat",'rb+')
found=False
try:
while True:
pos=fh2.tell()
stu1=pickle.load(fh2)
if stu1['Rollno']==key:
stu1['Marks']=int(input("Enter the Updated Marks "))
fh2.seek(pos)
pickle.dump(stu1,fh2)
found=True
print("The marks are updated::")
break
except EOFError:
if found==False:
print("The Searched Rollno does not exists:")
else:
print("Program Finished ")
fh2.close()
OUTPUT :
Q7.) Write a python program to implement
a stack using list.
CODING :
S=[]
c='y'
while (c=="y"):
print("1.PUSH")
print("2.POP")
print("3.DISPLAY")
choice=int(input("Enter your choice :"))
if (choice==1):
a=input("Enter any number :")
S.append(a)
elif (choice==2):
if(S==[]):
print("Stack Empty")
else :
print("Deleted element is :",S.pop())
elif (choice==3):
print(S)
else:
print("Wrong Input")
c=input("Do you want to continue or not?")
OUTPUT :
Q8.) Create a CSV file by entering user-id
and password, read and search the
password for given user id.
CODING :
import csv
with open("user_info.csv","w")as obj :
fileobj= csv.writer(obj)
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 end 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])
break
OUTPUT :
Q9.) Write a method in Python to read
lines from a text file “MYNOTES.txt” and
display those lines start with the alphabet
‘K’
CODING :
def display() :
file = open("MYNOTES.txt",'r')
line = file.readline()
while line :
if line[0]=='K' :
print(line)
line=file.readline()
file.close()
display()
OUTPUT :
Q10.) Write a function in python POP(Arr) ,
where Arr is a Stack implemented by a list
of number . This function returns the value
deleted from the Stack .
CODING :
def POP(Arr) :
# If stack is empty
if len(Arr)== 0 :
print("Underflow")
else :
L = len(Arr)
val = Arr.pop(L-1)
print("DELETED ELEMENT :",val)
Arr = [12,24,36,48,60]
POP(Arr)
POP(Arr)
OUTPUT :
Q11.) A binary file “Book.dat” has structure
[BookNo,Book_Name,Author,Price].
Write a user defined function CreateFile() to
input data for record and add to ‘Book.dat’.
CODING :
import pickle
def createFile():
c='y'
while c=='y':
fobj = open("Book.dat","ab")
BookNo= int(input("Book Number :"))
Book_name=input("Name :")
Author = input("Author :")
Price = int(input("Price :"))
rec=[BookNo,Book_n
ame,Author,Price]
pickle.dump(rec,fobj)
print("Data added successfully")
c= input("Do you want to enter more(y/n):")
fobj.close()
createFile()
OUTPUT :
Q12.) Program to input a string and count
the number of uppercase and lowercase
letters.
CODING :
# Program to count lowercase and uppercase letters in an inputted
string
str1 = input("Enter the string :")
print(str1)
upercase = 0
lwrcase = 0
i= 0
while i < len(str1):
if str1[i].islower() == True:
lwrcase += 1
if str1[i].isupper() == True :
upercase += 1
i += 1
print("No. of upercase letters in the string = ", upercase)
print("No. of lowercase letters in the string = ", lwrcase)
OUTPUT :
Q13.) Program to find maximum , minimum
, and mean value from the list .
CODING :
#Program to find maximum , minimum and mean value from the list.
list1 = []
n =int(input("Enter the number of element in the list :"))
i=0
while i < n :
x = int(input("Enter the elements of the list :"))
list1.append(x)
i = i+1
print(list1)
maximum = max(list1)
minimum = min(list1)
mean = sum(list1)/len(list1)
print("Maximum value is =",maximum)
print("Minimum value is =",minimum)
print("Average value is =",mean)
OUTPUT :
Q14.) Write a Python function to sum all
the items in a list .
CODING :
def sum_list(items) :
sum_numbers = 0
for x in items :
sum_numbers += x
return sum_numbers
a = sum_list([1,2,-8])
print("The Sum of numbers of all items in a list : ", a)
OUTPUT :
Q15.) Python program to search record for
given students name from csv file .
CODING :
import csv
f = open("Student.csv","r")
csv_reader = csv.reader(f) #csv_reader is the csv
reader object
name = input("Enter the name to be searched :")
for row in csv_reader :
if(row[0] == name ):
print(row)
OUTPUT :