Previous Index Next

Solved Examples - Text File Handling - I

Question 1

Write a method in python to write multiple line of text contents into a text file mylife.txt.

Program (write-multiple-lines.py)

def writelines():
    outfile = open('myfile.txt','w')

    while True:
        line = input('Enter line: ')
        line += '\n'
        outfile.write(line)
        choice = input('Are there more lines y/n? ')
        if choice == 'n':
            break
    outfile.close()

# Call the writelines function.
writelines()

Output

Enter line: Beautiful is better than ugly.
Are there more lines y/n? y
Enter line: Explicit is better than implicit.
Are there more lines y/n? y
Enter line: Simple is better than complex.
Are there more lines y/n? n

On opening the file myfile.txt the content of file will look like this:

Question 2

Write a function in Phyton to read lines from a text file diary.txt, and display only those lines, which are starting with an alphabet 'P'.

If the contents of file is :

I hope you will please write to me from all the cities you visit.
Please accept them with the love and good wishes of your friend.
He never thought something so simple could please him so much.

The output should be:

Please accept them with the love and good wishes of your friend.

Program (reading-lines.py)

def readlines():
    file = open('diary.txt','r')
    for line in file:
        if line[0] == 'P':
            print(line)

    file.close()

# Call the readlines function.
readlines()

Question 3

Write a method in Python to read lines from a text file INDIA.TXT, to find and display the occurrence of the word 'India'. For example, if the content of the file is:

India is the fastest-growing economy. India is looking for more investments around the globe. The whole world is looking at India as a great market. Most of the Indians can foresee the heights that India is capable of reaching.

The output should be 4.

Program (count-word.py)

def count_word():
    file = open('india.txt','r')
    count = 0

    for line in file:
        words = line.split()
        for word in words:
            if word == 'India':
                count += 1
        print(count)

    file.close()

# call the function count_word().
count_word()

Output

4


Previous Index Next