Python代码覆盖文件中的书面文本

问题描述 投票:0回答:1

我试图为Python编写一个代码,它要求俳句行,然后将其放入文件中,最后打印出内容,当我重用该代码时,它会覆盖文件中已有的俳句,所以我想保留之前的俳句。这也是在thonny。

这是我的代码:

haiku = open('Haiku.txt', 'w')
line1 = input('What is line one of the haiku: ')
line2 = input('What is line two of the haiku: ')
line3 = input('What is line three of the haiku: ')
print('=====', file = haiku)
print(line1, file = haiku)
print(line2, file = haiku)
print(line3, file = haiku)
print('=====', file = haiku)
haiku.close()
Haiku = open('Haiku.txt').read()
print(Haiku)

这是一个输出示例:

>>> %Run 'Haiku Maker.py'
What is line one of the haiku: The evening night,
What is line two of the haiku: The moon shining in the dark,
What is line three of the haiku: A serene scene.
=====
The evening night,
The moon shining in the dark,
A serene scene.
=====

但是当我添加另一个俳句并重新运行代码时,它会删除以前的俳句,而且我是初学者,所以请耐心等待。

python python-3.x thonny
1个回答
0
投票

将第一行替换为:

haiku = open('Haiku.txt', 'a')  # appends to existing file

© www.soinside.com 2019 - 2024. All rights reserved.