Stack
Stack
Stack
contents of a text file named ‘LINES . TXT’ and displays those lines from the
file which have at least 10 words in it.
Ans:
def LongLines():
f=open("lines.txt")
dt=f.readlines()
for i in dt:
if len(i.split())>10:
print(i)
f.close()
LongLines()
Write a function count Dwords ( ) in Python to count the words ending with a
digit in a text file ” Details . txt”.
Example:
Write a program in Python that defines and calls the following user-defined
functions :
i) Add_Book(): Takes the details of the books and adds them to a csv file
‘Book.csv‘. Each record consists of a list with field elements as book_ID, B_
name and pub to store book ID, book name and publisher respectively.
ii) Search_Book(): Takes publisher name as input and counts and displays the
number of books published by them.
Ans.:
a) Files are a limited resource managed by the OS, so it is important to close them
to avoid reaching the open limit and impacting program performance. Files left
unintentionally open become vulnerable to loss of data, and changes to files cannot
be readable until closed.
import csv
def Add_Book():
f=open("book.csv","a",newline='')
wo=csv.writer(f)
book_id=input("Enter Book ID:")
b_name=input("Enter Book Name:")
pub=input("Enter Publisher:")
wo.writerow([book_id,b_name,pub])
f.close()
def Search_Book():
f=open("book.csv",'r')
ro=csv.reader(f)
pn=input("Enter Publisher:")
cnt=0
for i in ro:
if i[2]==pn:
cnt+=1
print("Book ID:",i[0])
print("Book:",i[1])
print("Publisher:",i[2])
print("Total Books Published by ",pn," are:",cnt)
Add_Book()
Search_Book()