Python - 将数据附加到现有文件或读取文件

问题描述 投票:0回答:2

请编写一个充当简单日记的程序。日记条目应保存在文件 diary.txt 中。当程序执行时,它应该首先读取文件中已有的任何条目。

预期的输出可以在下面的屏幕截图中看到: enter image description here enter image description here 这是我的代码:

with open("diary.txt") as my_file:
    entries = my_file.read()
while True:
    operation = input("1 - add an entry, 2 - read entries, 0 - quit\nFunction:")
    if operation == "1":
        content = input("Diary entry: ")
        with open("diary.txt","a") as diary:
            diary.write(f"{content}\n")
        print("Diary saved\n")
    elif operation == "2":
        print("Entries: ")
        with open("diary.txt") as diary:
            for row in diary:
                print(row)
    elif operation == "0":
        print('Bye now!'+"\n")
        break

但是,当我提交给TMC时,它一试失败,并显示如下: 日记测试:test_1_exit_only 你的程序应该输出两行输入 0 现在它输出 现在再见!

任何人都可以帮我检查为什么我得到这样的结果吗? 非常感谢!

python readfile
2个回答
0
投票

完成练习时我也遇到了同样的问题。我浏览了

test_diary.py
文件以了解测试用例的执行方式并弄清楚了这一点。 对于最后一个
elif
条件,它要求用户按 0 退出,而不是
print
语句,您需要编写

print('Bye now!'+'\nBye now!')

导致错误的

assert
语句是这样的

self.assertTrue(
    len(output.split("\n")) == 2, 
    f"Your program should output two lines with input\n{input_value}\nNow it outputs\n{output}"
)

我相信这是他们的一个错误,因为输出的长度将为 1,但是,由于对于其他测试用例,他们没有检查退出语句“现在再见!”,它只对第一个情况重要,其中它的检查两次。 所以,做出改变应该会给你锻炼点。


0
投票

要通过测试用例,您可以应用上面的 hack 或只是修改您的代码,以便 功能选项与输入分开打印,如下所示。它将下面的 print 语句计为第 1 行,并将“Bye now!”的 print 语句计为第 1 行!如第 2 行。

print("1 - 添加条目,2 - 读取条目,0 - 退出") 函数 = 输入(“函数:”)

© www.soinside.com 2019 - 2024. All rights reserved.