【问题标题】:User reading and writing to a file [closed]用户读写文件[关闭]
【发布时间】:2018-07-24 14:27:59
【问题描述】:

我正在尝试编写一个程序,如果用户按 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.")

【问题讨论】:

  • “很遗憾,代码不能按我的预期工作。”为什么不?什么坏了?
  • 它在什么方面没有按预期工作?
  • 在python 3中,输入返回一个字符串而不是一个整数
  • input 总是返回一个字符串。您需要将其转换为 int 或检查字符串值,例如if user_input == '1':
  • @Tgsmith61591 代码没有执行 if 部分。

标签: python file


【解决方案1】:

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

if user_input == 1:

解决方案是使用int() 函数来获取正确的类型,即

if int(user_input) == 1:

更多阅读

Source 1

Source 2

【讨论】:

  • 谢谢。我之前确实使用过 use int() ,但代码根本没有运行。我会试试看。
  • @superv 您能否用“根本不运行”的意思更新您的原始问题?
  • 谢谢大家。我看到我之前没有添加一行代码。我已经做到了,还添加了 int() 转换。该代码似乎可以工作,但几乎没有我似乎找不到的错误。这是代码:
【解决方案2】:

问题是您的用户输入应该是 int。改用这个 :=>"user_input = int(input("请选择一个:"))" 而且您不能将整数写入文件,因此请使用:=> "readfile.write("user_input")" 或在写入文件之前将用户输入转换为字符串。

【讨论】:

  • 谢谢。我之前确实使用过 use int() 但代码根本没有运行。
  • readfile.write("user_input") 不会做他们想做的事。这不是如何转换为字符串
  • @roganjosh 是对的,它只是将字符串“user_input”写入文件。
  • 这只是一个例子
  • 我确实要求他在写入文件之前转换为字符串
猜你喜欢
  • 2013-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-02
  • 1970-01-01
相关资源
最近更新 更多