Python 用户读取和写入文件
我试图写一个程序,如果用户按1,它读取文件,如果按2,它写入文件,如果按3,它删除文件。不幸的是,代码在用户第一次输入后停止工作。有可能为此编写一个函数吗Python 用户读取和写入文件,python,file,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 on
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.")
Python3没有单独的
raw\u input()
和input()
函数来返回int
s和string
s。它只有返回字符串的input()
。您正试图将input()
(一个string
)的输出与int
的输出进行比较,例如在这一行:
if user_input == 1:
解决方案是使用int()
函数来获得正确的类型,即
if int(user_input) == 1:
更多阅读
问题是您的用户输入应该是int。请改用它:=>“user\u input=int(input(“请选择一个”)”
此外,您无法将整数写入文件,因此请使用以下命令:=>“readfile.write(“user\u input”)”或在写入文件之前将用户输入转换为字符串。“很遗憾,代码无法按我的预期工作。”为什么不这样做?有什么问题?它以什么方式没有按预期工作?在python 3中,input返回字符串而不是整数
input
始终返回字符串。您需要将其转换为int
或检查字符串值,例如if user\u input='1':
@Tgsmith61591代码未执行if部分。谢谢。我之前确实使用过use int(),但代码根本没有运行。readfile.write(“用户输入”)
不会执行他们想要的操作。这不是如何转换为string@roganjosh是的,它只是将字符串“user\u input”写入文件。这只是一个例子。我确实要求他在写入文件之前转换为字符串谢谢。我之前确实使用了int(),但代码根本没有运行。我会试试看。@superv你能不能用你说的“根本不跑”来更新你原来的问题?谢谢大家。我看到我之前没有添加一行代码。我已经完成了,还添加了int()转换。代码似乎可以工作,但几乎没有我找不到的错误。代码如下: