Wednesday, 9 April 2025

GRADE 12 : PRACTICAL 7 : TEXT FILES

 '''

WAP that initializes the file Independence.txt to :

"And that's how India became

independent on 15th August 1947.

INDIA owes her freedom to

the sacrifice of the freedom fighters."

Further, write functions to :

a) Accept and add lines to the existing file.Now display

the file

b) Copy the words that start with a consonant , to a

file called words1.txt.Display the file.

c) Display the line number and the line that contains

the word 'India'(case insensitive)

d) Edit the file to change freedom to uppercase(FREEDOM)

and display the file.

'''


txt='''And that's how India became

independent on 15th August 1947.

INDIA owes her freedom to

the sacrifice of the freedom fighters.

'''

fobj=open('independence.txt', 'w')

fobj.write(txt)

fobj.close()


def main():

    while True:

        print('''Menu:

1) Accept and add lines to the existing file.

2) Copy the words that start with a consonant ,to a file called words1.txt.

3) Display the line number and the line that contains the word 'India'(case insensitive)

4) Edit the file to change freedom to uppercase(FREEDOM)

5) Exit''')

        try:

            ch=int(input("Enter your choice:"))

            if ch==1:

                accept()

            elif ch==2:

                consonant()

            elif ch==3:

                display()

            elif ch==4:

                edit()

            elif ch==5:

                print("Program terminated!")

                break

        except Exception as e:

            print("Error: ",e,'!')


def accept():

    with open ('independence.txt', 'a') as fobj:

        n=int(input("Enter desired number of lines:"))

        print(f'Enter {n} lines:')

        for i in range (n):

            line=input()

            fobj.write(line+'\n')

    with open('independence.txt','r') as fobj:

        print(fobj.read())

        

def consonant():

    with open('independence.txt', 'r') as fobj:

        fobj1=open('word1.txt','w')

        txt=fobj.read()

        words=txt.split()

        for i in words:

            if i[0].isalpha() and i[0] not in 'aeiouAEIOU':

                fobj1.write(i+'\n')

        fobj1.close()

    with open('word1.txt','r') as fobj:

        print(fobj.read())

    

def display():

    with open('independence.txt', 'r') as fobj:

        txt=fobj.read()

        txt=txt.lower()

        lines=txt.splitlines()

        for i in range(len(lines)):

            if 'india' in lines[i]:

                print (i+1,'.',lines[i])


def edit():

    with open('independence.txt', 'r') as fobj:

        txt=fobj.read()

        txt=txt.replace('freedom','FREEDOM')

    with open('independence.txt','w') as fobj:

        fobj.write(txt)

    with open('independence.txt', 'r') as fobj:

        print(fobj.read())

main()


               

       



No comments:

Post a Comment