[go: up one dir, main page]

0% found this document useful (0 votes)
82 views14 pages

Python

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 14

Computer Science Programs

Contents

1. Read a text file line by line and display each word separated by a #.
2. Read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the file
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.
5. Create a binary file with roll number, name and marks. Input a roll number and
update the marks.
6. Write a random number generator that generates random numbers between 1
and 6 (simulates a dice).
7. Create a CSV file by entering user-id and password, read and search the
password for given user id.
8. Write a function to create a text file containing following data “Neither apple nor
pine are in pineapple. Boxing rings are square. Writers write, but fingers Don’t
fing. Overlook and oversee are opposites. A house can burn up as it burns down.
An Alarm goes off by going on.”
9. Read back the entire file content using read() or readlines () and display on
Screen.
10. Append more text of your choice in the file and display the content of file with
Line numbers prefixed to line.
11. Display last line of file.
12. Display first line from 10th character onwards.
13. Read and display a line from the file. Ask user to provide the line number to be
Read.
14. Write a program to read a file ‘Story.txt’ and create another file, storing an index
of Story.txt telling which line of the file each word appears in. If word appears
more than Once, then index should show all the line numbers containing the
word.
15. Write a program to accept a filename from the user and display all the lines from
the file which contain python comment character ‘#’.
16. Reading a file line by line from beginning is a common task, what if you want to
read a file Backward. This happens when you need to read log files. Write a
program to read and Display content of file from end to beginning.
17. Create a list/dictionary to store information of n different items, existing in a
shop. The Following data is to be stored w.r.t. each item code, name, price, qty.
Write a program to accept the data from user and store it permanently in the file.
Also provide user with facility of searching and updating the data in file based on
code of item
18. Following is the structure of each record in a data file named ”PRODUCT.DAT”.
{"prod_code":value, "prod_desc":value, "stock":value}. The values for prod_code
and prod_desc are strings, and the value for stock is an integer. Write a function
in PYTHON to update the file with a new value of stock. The stock and the
product_code, whose stock is to be updated, are to be input during the execution
of the function.
19. Given a binary file “STUDENT.DAT”, containing records of the following type:
[S_Admno, S_Name, Percentage] Where these three values are: S_Admno –
Admission Number of student (string) S_Name – Name of student (string)
Percentage – Marks percentage of student (float) Write a function in PYTHON
that would read contents of the file “STUDENT.DAT” and display the details of
those students whose percentage is above 75.
20. Assuming the tuple Vehicle as follows: ( vehicletype, no_of_wheels) Where
vehicle type is a string and no_of_wheels is an integer. Write a function
showfile() to read all the records present in an already existing binary file
SPEED.DAT and display them on the screen, also count the number of records
present in the file.
21. Write a function in PYTHON to search for a BookNo from a binary file
“BOOK.DAT”, assuming the binary file is containing the records of the following
type: {"BookNo":value, "Book_name":value} Assume that BookNo is an integer.
22. Write a function in PYTHON to search for a laptop from a binary file
“LAPTOP.DAT” containing the records of following type. The user should enter
the model number and the function should display the details of the laptop.
[ModelNo, RAM, HDD, Details] where ModelNo, RAM, HDD are integers, and
Details is a string.
23. Write a program to input a matrix of n rows and m columns. Find and display the
product of the corner values in it.
24. Write a program to input a matrix of n rows and m columns. Change and display
the matrix so that the 1st row is swapped with the last row.
25. Write a program to implement a stack to store phone numbers and names of n
employees with the following operations(menu driven): push(), pop(),
show_all()
26. Write a program to implement a stack to store phone numbers and names of n
employees with the following operations: deleteany(), insertafter(), show_all()
Q1. Read a text file line by line and display each word separated by a #.

Ans. filein = open("mydoc.txt",'r')


line =" "
while line:
line = filein.readline()
#print(line)
for w in line:
if w == ' ':
print('#',end = '')
else:
print(w,end = '')
filein.close()

output:
rita#
how#are#you#
>>>

Q2. Read a text file and display the number of vowels/ consonants/ uppercase/
lowercase characters in the file.

Ans. Def cnt ()


F=open(“D://test2.txt”,” r”)
Cont=F.read()
Print(cnt)
V=0
Cons=0
L_c_l=0
U_c_l=0
For ch in cont:
If(ch.islower())
L_c_l+=1
Elif(ch.isupper())
u_c_l+=1
ch=ch.lower()
if(ch in [a,e,I,o,u]):
v+=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]):
cons+=1
f.close()
print(“vowels are: “,v)
print(“constants are: “, cons)
print(“lower case letters are: “,L_c_l)
print(“upper case letters are: “,u_c_l)

output:
<function cnt at 0x01302300>
Vowels are : 23
Consonants are : 34
Lower case letters are: 57
Upper case letters are: 0
>>>

Q3. Remove all the lines that contain the character ‘a’ in a file and write it to another file.

Ans. fo=open("hp.txt","w")
fo.write("Harry Potter")
fo.write("There is a difference in all harry potter books We can see it as harry grows the
books were written by J.K Rowling ")
fo.close()

fo=open('hp.txt','r')
fi=open('writehp.txt','w')
l=fo.readlines()
for i in l:
if 'a' in i:
i=i.replace('a','')
fi.write(i)
fi.close()
fo.close()

output:
Hrry Potter There us difference in ll hrry potter books lthough I cn gree the books re
lwys better thn the movies
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.

Ans: import pickle


import sys
dict={}
def write_in_file():
file=open("D:\\stud2.dat","ab")  #a-append,b-binary
   no=int(input("ENTER NO OF STUDENTS: "))
   for i in range(no):
     print("Enter details of student ", i+1)
     dict["roll"]=int(input("Enter roll number: "))
      dict["name"]=input("enter the name: ")
     pickle.dump(dict,file)  #dump-to write in student file
    file.close()

Output:
>>>
MENU
 1-Write in a file
 2-display
 3-search
 4-exit

Enter your choice = 1


ENTER NO OF STUDENTS: 1
Enter details of student  1
Enter roll number: 1
enter the name: Abhijith
MENU
 1-Write in a file
 2-display
 3-search
 4-exit
Q5. Create a binary file with roll number, name, and marks. Input a roll number and
update the marks.

Ans: no_of_students=int(input("Enter no of students: "))


file=open("student0.dat","ab")
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 Student Marks: "))
pickle.dump(student_data,file)
student_data={}
file.close()
file=open("student0.dat","rb")
try:
while True:
student_data=pickle.load(file)
print(student_data)
except EOFError:
file.close()

Output:

Enter no. of students: 1


Enter roll no.: 7
Enter student name: Khushi
Enter student marks: 45
{‘roll no.’ : 3, ‘name’ : ‘arsh’, ‘marks’: 69}
{‘roll no.’ : 4, ‘name’ : ‘’, ‘jolly’: 69}
{‘roll no.’ : 5, ‘name’ : ‘sabby’, ‘marks’: 69}
{‘roll no.’ : 6, ‘name’ : ‘jogi’, ‘marks’: 69}
{‘roll no.’ : 7, ‘name’ : ‘khushi’, ‘marks’: 69}
Enter roll no. to search: 10
Roll no. not found please try again
Q6. Write a random number generator that generates random numbers between 1 and
6 (simulates a dice).

Ans. def random():


   import random
   s=random.randint(1,6)
   return s
print(random()) 

output

5
4
3

Q7. Create a CSV file by entering user-id and password, read and search the password
for given user id.

Ans. Import pickle


# 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("UserInformation.csv", "w", newline="\n")
writer=csv.writer(f1)
writer.writerows(List)
f1.close()

# opening the file to read the records


f2=open("UserInformation.csv", "r")
rows=csv.reader(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")
output:
Enter the user-id: user3
The password is:  password3

Q8. Write a function to create a text file containing following data “Neither apple nor
pine are in pineapple. Boxing rings are square. Writers write, but fingers Don’t fing.
Overlook and oversee are opposites. A house can burn up as it burns down. An Alarm
goes off by going on.”

Ans. In [ ]:
def readfile(filename):
f = open(file,'r+')
f.write('Neither apple nor pine are in pineapple. Boxing rings are square. Writers
write but fingers don’t fing. Overlook and oversee are opposites. A house can burn up as
it burns down. An alarm goes off by going on.')
f.seek(0)
content = f.readlines()
f.writelines(content)
for i in content:
print i
f.write('This is text of my choice')
f.seek(0)
content = f.readlines()
for i in xrange(len(content)):
print str(i) + content[i]
f.seek(10)
print f.read()
print content[-1]
linenumber = raw_input('Enter line number: ')
print content[linenumber]
f.close()

output:
Q9. Read back the entire file content using read() or readlines () and display on Screen.

Ans. filepath = 'Iliad.txt'


with open(filepath) as fp:
line = fp.readline()
cnt = 1
while line:
print("Line {}: {}".format(cnt, line.strip()))
line = fp.readline()
cnt += 1
output:
Line 567: exceedingly trifling. We have no remaining inscription earlier than the
Line 568: fortieth Olympiad, and the early inscriptions are rude and unskilfully
Line 569: executed; nor can we even assure ourselves whether Archilochus, Simonides
Line 570: of Amorgus, Kallinus, Tyrtaeus, Xanthus, and the other early elegiac and
Line 571: lyric poets, committed their compositions to writing, or at what time the
Line 572: practice of doing so became familiar. The first positive ground which
Line 573: authorizes us to presume the existence of a manuscript of Homer, is in the
Line 574: famous ordinance of Solon, regarding the rhapsodies at the
Line 575: Panathenaea: but for what length of time previously manuscripts had
Line 576: existed, we are unable to say.

Q10. Append more text of your choice in the file and display the content of file with Line
numbers prefixed to line.

Ans. def file_read(fname):

from itertools import islice


with open(fname, "w") as myfile:
myfile.write("Python Exercises")
myfile.write("Java Exercises")
txt = open(fname)
print(txt.read())
file_read('abc.txt')

output:

Python Exercises
Java Exercises
Q11. Display last line of file.

Ans. def read_lastnlines(fname,n):


with open('file1.txt') as f:
for line in (f.readlines() [-n:]):
print(line)

read_lastnlines('file1.txt',3)

Output:
This is the last line

Q12. Display first line from 10th character onwards.

Ans. f = open("textfile.txt")
lines = f.readlines()
linesingle = f.readline()
for line in lines:
print (line)

if "2020-01-28 " in line:


print("EXISTS")

output:
Q13. Read and display a line from the file. Ask user to provide the line number to be
Read.

Ans. fp = open("file")
for i, line in enumerate(fp):
if i == 25:
# 26th line
elif i == 29:
# 30th line
elif i > 29:
break
fp.close()

output:

Q14. Write a program to read a file ‘Story.txt’ and create another file, storing an index of
Story.txt telling which line of the file each word appears in. If word appears more than
once, then index should show all the line numbers containing the word.

Ans. file1 = open("story.txt","r")

file2 = open("Path walla.txt","w")


data = file1.readlines()
for line in data :
words = line.split()
for j in words :
file2.write( j )
file2.write(" = ")
file2.write( "index :- " + str ( line.index( j ) ) + " line:- " + str(data.index( line) +1 ) )
file2.write( "\n" )

file1.close()
file2.close()
Q15. Write a program to accept a filename from the user and display all the lines from
the file which contain python comment character ‘#’.

Ans. user = input("Enter file name :-")


f = open(user + ".txt",'r')

data = f.readlines()
for i in data :
if "#" in i :
print(i)

f.close()

output:

Q16. Reading a file line by line from beginning is a common task, what if you want to
read a file Backward. This happens when you need to read log files. Write a program to
read and Display content of file from end to beginning.

Ans. Hello=input("Enter file name: ")


for line in reversed(list(open(hello))):
print(line.rstrip())

output:
Enter file name: read.txt
hello
hello word

Q17. Create a list/dictionary to store information of n different items, existing in a shop.


The Following data is to be stored w.r.t. each item code, name, price, qty. Write a
program to accept the data from user and store it permanently in the file. Also provide
user with facility of searching and updating the data in file based on code of item.

Ans.
Q18. Following is the structure of each record in a data file named ”PRODUCT.DAT”.
{"prod_code":value, "prod_desc":value, "stock":value}. The values for prod_code and
prod_desc are strings, and the value for stock is an integer. Write a function in PYTHON
to update the file with a new value of stock. The stock and the product_code, whose
stock is to be updated, are to be input during the execution of the function.

Q23. Write a program to input a matrix of n rows and m columns. Find and display the
product of the corner values in it.

Ans. R = int(input("Enter the number of rows:"))


C = int(input("Enter the number of columns:"))

matrix = []
print("Enter the entries rowwise:")

for i in range(R):
a =[]
for j in range(C):
a.append(int(input()))
matrix.append(a)

for i in range(R):
for j in range(C):
print(matrix[i][j], end = " ")
print()

output:
Enter the number of rows:2
Enter the number of columns:3
Enter the entries row wise:
1
2
3
4
5
6

123
456
Q25. Write a program to implement a stack to store phone numbers and names of n
employees with the following operations(menu driven): push(), pop(), show_all().

Ans.

You might also like