CBSE Class 12 Computer Science Question 134 of 145

File Handling — Question 14

Back to all questions
14
Question

Question 14

Write a program that will create an object called filout for writing, associate it with the filename STRS.txt. The code should keep on writing strings to it as long as the user wants.

Answer
with open('STRS.txt', 'w') as filout:
    ans = 'y'
    while ans == 'y':
        string = input("Enter a string: ")
        filout.write(string + "\n")  
        ans = input("Want to enter more strings?(y/n)...")    
Output
Enter a string: Hello
Want to enter more strings?(y/n)...y
Enter a string: world!
Want to enter more strings?(y/n)...n

The file "STRS.txt" includes:

Hello
world!