English

In the code (given above), the word END used to indicate end of word list is also stored in the file. Modify the code so that end is not stored in the file.

Advertisements
Advertisements

Question

file = open('textfile.txt','w')
word = ''
while word.upper() != 'END':
     word = raw_input('Enter a word use END to quit')
     file.write(word + '\n')
file.close()

In the code (given above), the word END used to indicate end of word list is also stored in the file. Modify the code so that end is not stored in the file.

Code Writing
Advertisements

Solution

with open("textfile.txt", "w") as file:
    while True:
        word = input("Enter a word (END to quit): ")
        if word.upper() == "END":
            break
        file.write(word + "\n")

The termination test is performed before write(), so END is not stored.

shaalaa.com
  Is there an error in this question or solution?
Chapter 7: Data File Handling - EXERCISE [Page 145]

APPEARS IN

CBSE Computer Science with Python [English] Class 12
Chapter 7 Data File Handling
EXERCISE | Q 12. | Page 145
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×