Skip to main content

CS - XII - TEXT FILES - PRACTICE QUESTIONS - 21 JULY

 

TEXT FILES

PRACTICE QUESTIONS


1. Write a Python function that Count total number of vowels in a file “abc.txt”.

 def count_vowels():

    count = 0

    with open("abc.txt", "r") as F:

        S = F.read()

        for x in S:

            if x.lower() in "aeiou":

                count += 1

    print("Total number of vowels are:", count)

count_vowels()

2. function that extracts and displays all the words from a text file named "text.txt" which begin with a vowel (A, E, I, O, U – both uppercase and lowercase):

def vowel_words():

    vowels = 'AEIOUaeiou'

    file = open("text.txt", "r")  # Open the file in read mode

    content = file.read()

    file.close()  # Close the file

    words = content.split()  # Split the content into words

    print("Words starting with a vowel:")

    for word in words:

        if word[0] in vowels:

            print(word)

vowel_words()


3.Write a Python function longest_word() that reads text from a file "words.txt" and returns the longest word in the file.

file = open("text.txt", "r")     

content = file.read()   

print(content)           

file.close()                       

words = content.split()           # Step 4: Split text into a list of words

max_word = " "                      # Step 5: Start with an empty longest word

for word in words:                 

    if len(word) > len(max_word): 

        max_word = word

print(max_word)


4.Python function named govWeb() that reads a file called URLs.txt and displays all the words that contain "gov.in"

def govWeb():

    file = open("text.txt", "r")       

    content = file.read()             

    file.close()          

            

    words = content.split()           

    print("Words containing 'gov.in':")

    for word in words:

        if "gov.in" in word:

            print(word)

govWeb()

5.Write a UDF count_the() to read a text file text.txt and count no.of times the word the/The is appearing in the file

def count_the():

    f = open("C:/Users/Kirti Hora/Desktop/TFILE/text3.txt","r")

    ctr= 0

    str= f.read()

    wdlist= str.split()

    for wd in wdlist:

        if wd== "the" or wd=="The":

                     ctr+=1

    print("No of THE present in the file are -",ctr)

    f.close()

count_the()


6.Python function that reads a text file named Alpha.txt and displays only the lines that begin with the word "You"

def display_you():

    file = open("Alpha.txt", "r")  # Open the file

    for line in file:

        if line[:3] == "You":      # Check if first 3 characters are "You"

            print(line, end="")    # Print the matching line

    file.close()                   # Close the file

OR

def display_you():
    file = open("Alpha.txt", "r")  # Open file in read mode

    for line in file:
        if line.startswith("You"):
            print(line, end="")    # Print the line (end="" avoids double newlines)

    file.close()                  # Close the file


7.Python function that reads from "Words.txt" and displays all words longer than 5 characters

def long_words():

    file = open("C:/Users/Kirti Hora/Desktop/TFILE/text3.txt", "r")  # Open the file in read mode

    for line in file:

        words = line.split()  # Split line into individual words

        for word in words:

            if len(word) > 5:

                print(word)

    file.close()  # Close the file

long_words()


8. Write a method/function DISPLAYWORDS() in python to read lines from a text file STORY.TXT, and display those words, which are less than 4 characters.

9.Write a function in python to count the number of lines in a text file 'STORY.TXT' which is starting with an alphabet 'A'.

def count_A():

    count = 0

    file = open("text.TXT", "r")  # Open the file in read mode


    for line in file:

        if len(line) > 0 and line[0] == 'A':  # Check if line starts with 'A'

            count += 1


    file.close()  # Close the file

    print("Number of lines starting with 'A':", count)

count_A()


Q: Difference Between r+ and w+ modes

r+ Mode in Python File Handling: 

The r+ mode is used to open a file for both reading and writing.

·       The file must already exist. If it does not, Python will raise a FileNotFoundError.

·       The file pointer is placed at the beginning of the file.

·       You can read from and write to the file.

·       When you write, it overwrites the content from the current file pointer onward (it doesn't insert).


Meaning of "w+" Mode:

Opens the file for both writing and reading.

Creates the file if it does not exist.

Overwrites the file (deletes all existing content) if it already exists.

The file pointer is placed at the beginning of the file.



Comments

Popular posts from this blog

PYTHON - MYSQL CONNECTIVITY CODE

  #INSERTION OF DATA import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="root", database="school" ) print("Successfully Connected") #print(mydb) mycursor=mydb.cursor()   v1=int(input("enter ID:")) v2=input("enter name:") v3=input("enter Gender:") v4=int(input("enter age:")) sql='insert into TEACH values("%d","%s","%s","%s")'%(v1,v2,v3,v4) print(sql) mycursor.execute(sql) mydb.commit() print("record added") #MYSQL Connection code – Deletion on database SOURCE CODE: s=int(input("enter id of TEACHER to be deleted:")) r=(s,) v="delete from TEACH where id=%s" mycursor.execute(v,r) mydb.commit() print("record deleted") MYSQL Connection code – Updation on database SOURCE CODE: import mysql.connector mydb = mysql.connector.c...

REVISION IF CONSTRUCT | CLASS TEST

                                                                                     CLASS TEST 1. Write a Python program that asks the user for their age, gender, and current fitness level (beginner, intermediate, or advanced). Based on this information, suggest a suitable fitness plan using if-else statements. Requirements: Inputs : Age (integer) Gender (male/female) Fitness level (beginner/intermediate/advanced) Outputs : Recommend a fitness plan that includes: Suggested workout duration. Type of exercises (e.g., cardio, strength, flexibility). Rest days. Logic : Use if-else to determine the plan based on conditions such as: Age group (e.g., <18, 18–40, >40). Fitness leve...