当用户在python中输入q时,从文本文件中删除q

2024-05-20 01:06:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试创建一个文本文件来询问用户名,并将每个用户名存储在该文件的新行中。现在,由于使用while循环执行用户输入的次数不限,我为用户创建了一个quit选项,让用户输入q以退出。。。。随时都可以。完成此任务后,当我打开文本文件“guest”_书本.txt“我想去掉结尾行‘q’。你知道吗

通常对于列表,我们使用像[elt for elt in filename if elt not in'q']这样的模式,这样可以消除'q'。如何使用文本文件?如有任何意见,我们将不胜感激!!!你知道吗

这是我的密码:

filename='guest_book.txt'

with open(filename,'a') as file_object:

    while True:
        user_name = input("Enter your name: ")
        file_object.write(user_name)
        file_object.write('\n')

Tags: 文件用户nameintxtobjectfilename用户名
2条回答

最好的方法是插入一个中断

while True:
    user_name = input("Enter your name: ")
    if user_name=="q":
        break
    file_object.write(user_name)
    file_object.write('\n')

你可以这样做

user_name=None
while not user_name == "q":
    user_name = input("Enter your name: ")
    file_object.write(user_name)
    file_object.write('\n')

但休息可能是这里最好的做法

以下是我的解决方案:

filename='guest_book.txt'

# Edit 1
with open(filename, 'a') as file_object:

    while True:
        user_name = input("Enter your name: ")

        if user_name == 'q':
            break

        else:
            file_object.write(user_name)
            file_object.write('\n')

有了这段代码,当它将用户名识别为“q”时,它会立即中断,而不会将“q”写入文件。你知道吗

相关问题 更多 >