2017-03-02 97 views
0

使用此程序时,我试图将条目添加到空文本文件中。下面是我的代码:使用While循环在Python中添加/添加文件

###Adding to an Empty File 
filename = 'guest_book.txt' 

message = input("Please enter your name for our records: ") # retrieving input 

while message != 'finished': # checking for value that will end the program 
    with open(filename, 'a') as f: 
     f.write(message) 

程序正确建立,但一旦我输入一个名字,什么也不会发生,且该文本文件保持为空。有任何想法吗?

回答

0

您请求消息一次,然后开始循环查找消息finished。但是,如果您第一次输入了与message不同的东西,则此情况永远不会成立。

我怀疑你想:

###Adding to an Empty File 
filename = 'guest_book.txt' 

while True: # checking for value that will end the program 
    message = input("Please enter your name for our records: ") # retrieving input 
    if message == 'finished': 
     break 
    with open(filename, 'a') as f: 
     f.write(message) 
+0

我的输出量混乱了,所以我不得不增加了一些带()方法。否则,这工作!谢谢! –