将键盘输入的内容逐行写入文件,当输入Quit时程序终止运行。
该回答引用chatgpt:
file_name = "input.txt"
with open(file_name, "w") as file:
while True:
line = input("请输入内容(输入'Quit'结束):")
if line == "Quit":
break
file.write(line + "\n")
print("程序已结束运行。")
可以使用Python中的文件操作来实现这个功能。具体思路是:不断读取键盘输入,如果输入是Quit,则终止程序运行,否则将输入内容写入文件。
以下是实现代码:
filename = "output.txt" # 文件名
with open(filename, "w") as f:
while True:
line = input() # 读取键盘输入
if line == "Quit":
break # 终止程序
f.write(line + "\n") # 写入文件
代码中使用了Python的open函数来打开文件,并使用with语句来确保文件操作完成后自动关闭文件。while循环不断读取键盘输入,并判断是否为Quit,如果是则break退出循环,否则将输入内容写入文件。为了每行内容都写入文件,使用\n来表示换行符。
运行程序后,每次输入一行内容并敲击回车,程序就会将该行内容写入文件。当输入Quit时,程序终止运行。最终生成的文件名为output.txt,文件内容即为输入的所有行。
with open("result.txt", mode="w", encoding="utf-8") as f:
while True:
your_input = input("Please enter: ")
if your_input.lower() == "quit":
break
else:
f.write(your_input)
f.write("\n")