You are on page 1of 3

Write the definition of a Python function named LongLines( ) which reads the

contents of a text file named ‘LINES . TXT’ and displays those lines from the
file which have at least 10 words in it.

For example, if the content of ‘ LINES . TXT ‘ is as follows :


3

Once upon a time, there was a woodcutter

He lived in a little house in a beautiful, green wood.

One day, he was merrily chopping some wood.

He saw a little girl skipping through the woods, whistling happily.

The girl was followed by a big gray wolf.

Then the function should display output as :

He lived in a little house in a beautiful, green wood.

He saw a little girl skipping through the woods, whistling happily.

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:

If the file content is as follows :

On seat2 VIP 1 will sit and

On seat1 VVIP2 will be sitting

Output will be:


Number of words ending with a digit are 4
def Dwords():
f=open("details.txt")
dt=f.read()
w=dt.split()
c=0
for i in w:
if i[-1].isdigit():
c+=1
print("Number of words ending with digit are:",c)
Dwords()

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()

You might also like