用户读取和写入文件

时间:2018-07-24 14:27:59

标签: python file

我正在尝试编写一个程序,如果用户按1,它将读取文件,如果2,则写入文件,如果3,则擦除文件。不幸的是,代码在用户的首次输入后停止工作。可以为此编写函数吗?

while True:
    print("(1) Read the notebook")
    print("(2) Add note")
    print("(3) Empty the notebook")
    print("(4) Quit")

    user_input = input("Please select one: ")

    if user_input == 1:
        readfile = open("notebook.txt","r")
        content = readfile.read()
        print(content)
        readfile.close()

    elif user_input == 2:
        new_input = input("Write a new note: ")
        readfile = open("notebook.txt", "a")
        readfile.write(new_input)
        readfile.close()

    elif user_input == 3:
        readfile = open("notebook.txt", "w")
        readfile.close()

    elif user_input == 4:
        break

print("Notebook shutting down, thank you.")

2 个答案:

答案 0 :(得分:0)

Python3没有用于返回raw_input()input()的单独的intstring函数。它只有input(),它返回一个字符串。您正在尝试将input()string)和int的输出进行比较,例如在此行上:

if user_input == 1:

解决方案是使用int()函数正确选择类型,即

if int(user_input) == 1:

更多阅读内容

Source 1

Source 2

答案 1 :(得分:0)

问题是您的用户输入应为int。改用它:=>“ user_input = int(input(”请选择一个:“))” 同样,您也不能将整数写入文件,因此请使用以下命令:=>“ readfile.write(” user_input“)”,或在写入文件之前将用户输入转换为字符串。