2017-09-26 7 views
1

私はPythonには新しく、ループと条件について学習しています。Pythonでの文字列のループが期待通りに動作しない

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() 

今、私は「終了」を入力するたびに、私はそれがループの外に出ることを期待するだろうが、何らかの理由で、そうでない:私は、コードを持っています。それは無限ループのように見えるものです。その背後にある理由は何でしょうか?前もって感謝します。

答えて

2

readline()を使用してみてくださいは\n改行文字が含まれています。

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' 

か、"exit\n"にこの

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) 
0

それが正確に何を見るためにappendを印刷、またはappend = str(sys.stdin.readline())

1

変更条件のようなことを書いて実行する可能性があります。それは私のために働いた。

関連する問題