写入文件将覆盖内容

2024-04-20 14:02:03 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,当我运行这段代码时,它工作得很好,但是它覆盖了stopwatch_times.txt中以前的时间,所以,我搜索了高和低,但是couldn't找到了如何做。你知道吗

#!/usr/bin/python
import time

var_start = input("Press Enter To START The stopwatch")
t0 = time.time()
var_stop = input("Press Enter to STOP The stopwatch")

stopwatch_time = round(time.time() - t0,2)
stopwatch_time = str(stopwatch_time)

file_ = open("stopwatch_times.txt")
with open('stopwatch_times.txt', 'w') as file_:
    file_.write(stopwatch_time)

print ("Stopwatch stopped - Seconds Elapsed : ",round(time.time() - t0,2))

Tags: the代码txtinputtimevar时间open
2条回答

尝试:

open('stopwatch_times.txt', 'a')

有关更多信息,请查看7.2章节。在https://docs.python.org/2/tutorial/inputoutput.html读写文件

必须以'a'模式打开文件才能附加到该文件:

with open('stopwatch_times.txt', 'a') as file_:
    ...  # Write to the file.

现在它将一个接一个地列出次。如果换行符有问题,请确保将系统的换行符添加到行中。你知道吗

相关问题 更多 >