Click here to Skip to main content
15,886,578 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to Read lines of input from the user. When the user enters “stop”, write all the strings to a file. The string entered last should be written first in the file. Each string should be written as a single line in the file.

What I have tried:

Python
textfile = open("jkl.txt","w")
lines=""
while lines!="stop":
    lines = input("Enter lines of input: ").split()
    if "stop" not in lines:
        for line in reversed(lines):
            textfile.writelines(line)
    else:
            break
Posted
Updated 19-Jan-22 8:52am
v2
Comments
CHill60 19-Jan-22 3:50am    
That's what your code appears to do. What is the problem or question?

The Python input function reads a line at a time from the user, not multiple lines - so each time round your loop, you read a single line, check if it is "stop" and print it reversed (which does nothing for a single line) to your output file.

What you need to do is read lines in a loop until you get stop, storing each line into a collection as you go.
After that loop, you can reverse the collection and write your lines in reverse order to the file, but not until then!
 
Share this answer
 
Try this, should give you an idea

Python
stack = []
lines=''
textfile = open("jkl.txt","w")
while lines!='stop':
    lines = input("Enter lines of input: ")
    if lines == 'stop':
        while len(stack) > 0: 
            outString = stack.pop() + '\n'
            textfile.write('outString')
            print(outString)
    else:
        stack.append(lines)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900