Sunday, 2 November 2025

Text file practice

''' Write a function in Python that copies the book names having ‘Y’ or ‘y’ in

their name from a text file

“Bookname.txt” into another file Yy.txt Finally display Yy.txt and the total

number of Books in the text..

Example:

If the file ‘Bookname.txt’ contains the names of following books :

One Hundred Years of Solitude

The Diary of a Young Girl

On the Road

After execution, the output will be :

One Hundred Years of Solitude

The Diary of a Young Girl

No of Books in Yy.txt : 2'''


def func():

    l=[]

    with open('bookname.txt','r') as f:

        text=f.read()

        lines=text.splitlines()

        for i in lines:

            if 'y' in i or 'Y' in i:

                l.append(i)


    with open('yy.txt','w') as f:

        f.writelines(l)


    with open('yy.txt','r') as f:

        text=f.read()

        lines=text.splitlines()

        print(text)

        print('no of books : ',len(lines))



'''

Write a function RevString() to read a textfile “Input.txt” and prints the words starting with

‘O’ in reverse order. The rest of the content is displayed normally.


Example:

If content in the text file is :

UBUNTU IS AN OPEN SOURCE OPERATING SYSTEM



Output will be :

UBUNTU IS AN NEPO SOURCE GNITAREPO SYSTEM

(words ‘OPEN’ and ‘OPERATING’ are displayed in reverse order)

'''       

with open('input.txt','r') as f:

        text=f.read()

        s=''

        words=text.split()

        for i in words:

            if i[0].lower()=='o':

                s=s+i[::-]+' ')

            else:

                s=s+i

print(s)


No comments:

Post a Comment