1

I'm new to Python and I'm learning about loops and conditions. I have the code:

import random
import sys
import os

test_file = open("test.txt", "wb") #use wb if write

append = ""
while append != "exit":
    print("Write something to append to file: ")
    append = sys.stdin.readline()
    test_file.write(bytes(append, 'UTF-8'))

test_file.close()

Now, whenever I type in 'exit', I would expect it to exit out of the loop, but for some reason, it doesn't. It continues to be what seems like an infinite loop. What could be the reason behind it? Thanks in advance.

3 Answers 3

2

readline() includes the \n newline character.

You could use append.strip().

In [1]: import sys

In [2]: append = sys.stdin.readline()
test

In [3]: append
Out[3]: 'test\n'

In [4]: append.strip()
Out[4]: 'test'

or you could write that like this

with open("test.txt", "w") as test_file:
    while True:
        print("Write something to append to file: ")
        append = input()
        if len(append) == 0 or input.strip() == "exit":
            break   
        test_file.write(append)
Sign up to request clarification or add additional context in comments.

Comments

1

Change condition to "exit\n" and execute. It worked for me.

Comments

0

try printing append to see exactly what it is, or using append = str(sys.stdin.readline())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.