输出:
很抱歉,当我尝试将我的Python代码粘贴到此论坛帖子的代码框中时,这非常尴尬。
代码:
# update three quotes to a file
file_name = "my_quote.txt"
# create a file called my_quote.txt
new_file = open(file_name, 'w')
new_file.close()
def update_file(file_name, quote):
# First open the file
new_file = open(file_name, 'w')
new_file.write("This is an update\n")
new_file.write(quote)
new_file.write("\n\n")
# now close the file
new_file.close()
for index in range(3):
quote = input("Enter your favorite quote: ")
update_file(file_name, quote)
# Now print the contents to the screen
new_file = open(file_name, 'r')
print(new_file.read())
# And finally close the file
new_file.close(
答案 0 :(得分:0)
你应该使用append而不是write。当您使用write时,它会创建一个新文件,无论之前有什么。试试new_file = open(file_name, 'a')
答案 1 :(得分:0)
为什么只将最后一个输入写入txt?
每次执行open(file_name, 'w')
时,它都会清除文件的内容并开始从文件的开头写入。
如果您想将新内容添加到该文件中
open(file_name, 'a')
答案 2 :(得分:0)