简体   繁体   English

使用 while 循环将用户 output 保存到文件

[英]Saving user output to file with while loop

I'm going through some exercises and I can't just figure this out.我正在做一些练习,但我无法弄清楚这一点。

Write a while loop that prompts users for their name.编写一个提示用户输入姓名的 while 循环。 When they enter their name, print a greeting to the screen and add a line recording their visit in a file called guest_book.txt.当他们输入他们的名字时,在屏幕上打印一个问候语,并在一个名为 guest_book.txt 的文件中添加一行记录他们的访问。 Make sure each entry appears on a new line in the file.确保每个条目出现在文件的新行上。

Honestly, I spent way to much time on that and it seems like I'm not understanding the logic of working with files.老实说,我花了很多时间在这上面,似乎我不理解处理文件的逻辑。 I think the f.write should be directly under with open in order for the user input to be saved in the file but that's as much as I know.我认为f.write应该直接在with open下,以便将用户input保存在文件中,但这就是我所知道的。 Can you please help me?你能帮我么?

My attempts:我的尝试:

filename = 'guest_book.txt'

with open(filename, 'w') as f:
    lines = input('Input your name to save in the file: ')
    while True:
        for line in lines:
            f.write(input('Input your name to save in the file'))

I had some more hopes for the second one but still doesn't work.我对第二个抱有更多希望,但仍然没有成功。

filename = 'guest_book.txt'
prompt = "Input your name to be saved in guest book: "
active = True

with open(filename, 'w') as f:
    while active:
        message = f.write(input(prompt))

        if message == 'quit':
            break
        else:
            print(message)

A bit of rejigging will get the code as you've written it to work.一些重新调整将使您编写的代码可以正常工作。 The main issue is that you can't use the output of f.write() as the value of message, as it doesn't contain the message, it contains the number of characters written to the file, so it will never contain quit .主要问题是你不能使用f.write()的 output 作为 message 的值,因为它不包含消息,它包含写入文件的字符数,所以它永远不会包含quit . Also, you want to do the write after you have checked for quit otherwise you will write quit to the file.此外,您希望在检查完quit后进行write ,否则您将quit写入文件。

filename = 'guest_book.txt'
prompt = "Input your name to be saved in guest book: "
active = True

with open(filename, 'w') as f:
    while active:
        message = input(prompt)

        if message == 'quit':
            active = False
        else:
            f.write(message + '\n')
            print(message)

Note: I have changed the break to active = False as you have written it as while active: , but you would have been fine with just while True: and break注意:我已将break更改为active = False ,因为您已将其编写为while active: ,但是您可以只使用while True:break

You can use open(filename, 'a') when a stands for append that way you can append a new line to the file each loop iteration.当 a 代表 append 时,您可以使用open(filename, 'a')这样您就可以在每次循环迭代时在文件中添加新行 append 。

see: How do you append to a file in Python?请参阅: 您如何将 append 转换为 Python 中的文件?

To learn about file handling see: https://www.w3schools.com/python/python_file_handling.asp要了解文件处理,请参阅: https://www.w3schools.com/python/python_file_handling.asp

Good luck!祝你好运!

filename = 'guest_book.txt'
prompt = "Input your name to be saved in guest book: "
active = True

with open(filename, 'w') as f:
    while active:
        message = input(prompt)

        if message == 'quit':
            break
        else:
            print(message)
        
        f.write(message + '\n')

This might work.这可能会奏效。 Assigning message = f.write(...) will make its value the return value of f.write().分配message = f.write(...)将使其值成为 f.write() 的返回值。

Try this..尝试这个..

filename = 'guest_book.txt'
name = ''

with open(filename, 'w') as f:
    while name != 'quit':
        name = input('Input your name to save in the file: ')
        if(name == 'quit'):
            break
        f.write(name + '\n')

For anyone wondering how to solve the whole thing.对于任何想知道如何解决整个问题的人。 We're using append instead of write in order to keep all the guests that have been using the programme in the past.我们使用 append 而不是写来保留过去一直使用该程序的所有客人。 Write would override the file.写入将覆盖文件。

filename = 'guest_book.txt'

print("Enter 'quit' when you are finished.")
while True:
    name = input("\nWhat's your name? ")
    if name == 'quit':
        break
    else:
        with open(filename, 'a') as f:
            f.write(name + "\n")
        print(f"Hi {name}, you've been added to the guest book.")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM