Previous Index Next

Solved Examples - Text File Handling - II

Question 1

Assuming that a text file named first.txt contains some text written into it, write a function that reads the file first.txt and creates a new file named second.txt, to contain only those words from the file first.txt which start with a lowercase vowel (i.e. with 'a', 'e', 'i', 'o', 'u').

For example if the file first.txt contains
Carry umbrella and overcoat when it rains

Then the file second.txt shall contain
umbrella and overcoat it

Program (copy-file.py)

def copy_file():
    infile = open('first.txt','r')
    outfile = open('second.txt','w')

    for line in infile:
        words = line.split()
        for word in words:
            if word[0] in 'aeiou':
                outfile.write(word + ' ')
                
    infile.close()
    outfile.close()

# Call the copy_file function.
copy_file()

Question 2

Write a function in Python to count and display number of vowels in text file.

Program (vowels.py)

def count_vowels():
    infile = open('first.txt','r')
    count = 0
    data = infile.read()
    for letter in data:
        if letter in 'aeiouAEIOU':
            count += 1

    print('Number of vowels are',count)            
    infile.close()
    
# Call the count_vowels function.
count_vowels()

Previous Index Next