Python
Python
Python
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 #.
output:
rita#
how#are#you#
>>>
Q2. Read a text file and display the number of vowels/ consonants/ uppercase/
lowercase characters in the file.
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.
Output:
>>>
MENU
1-Write in a file
2-display
3-search
4-exit
Output:
output
5
4
3
Q7. Create a CSV file by entering user-id and password, read and search the password
for given user id.
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.
Q10. Append more text of your choice in the file and display the content of file with Line
numbers prefixed to line.
output:
Python Exercises
Java Exercises
Q11. Display last line of file.
read_lastnlines('file1.txt',3)
Output:
This is the last line
Ans. f = open("textfile.txt")
lines = f.readlines()
linesingle = f.readline()
for line in lines:
print (line)
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.
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 ‘#’.
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.
output:
Enter file name: read.txt
hello
hello word
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.
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.