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

GRADE XII - Python Connectivity with MySQL

  Python Connectivity with MySQL In real-life applications, the data inputted by the user and processed by the application needs to be saved permanently, so that it can be used for future manipulation. Usually, input and output data is displayed during execution but not stored, as it resides in main memory , which is temporary — i.e., it gets erased once the application is closed. This limitation can be overcome by sending the data to be stored in a database , which is made accessible to the user through a Front-End interface . Key Concepts Database A database is an organized collection of data that is stored and accessed electronically from a computer system. DBMS (Database Management System) A DBMS is software that interacts with end-users, applications, and the database to capture and analyze data. Front-End The Front-End is the user interface of the application, responsible for input/output interaction with the user. Back-End The Back-End refe...

GRADE XI | DESIGN THINKING & INNOVATION (848) | INTRO | CH-1

  DESIGN THINKING &  INNOVATION (848)  INTRODUCTION LINK : INTRODUCTION PPT PPT LINK Notes: Design Thinking and Innovation Grade XI Introduction Section   I. What is Design? (0.1.1) Definitions from Experts: John Maeda: "Design is solution to a problem". Saul Bass: "Design is thinking made visual". Charles Eames:   “Design is a plan for arranging elements in such a way as best to accomplish a particular purpose.” Steve Jobs:  "Design is not just what it looks like and feels like. Design is how it works". Prof. Sudhakar Nadkarni:  "Essentials of design are— purity, precision, details". Design is a way of understanding needs, identifying problems, and creating appropriate and innovative solutions. It is not only about appearance, but also about usefulness and sustainability. Design is explained as something that helps solve problems and make a positive difference. Key ...