写入文件会覆盖内容

时间:2015-04-11 09:37:53

标签: python python-3.x

因此,当我运行此代码时,它可以完美地运行,但它会覆盖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))

2 个答案:

答案 0 :(得分:4)

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

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

现在它会一个接一个地列出时间。如果您遇到换行问题,请确保将系统的正确换行符添加到该行。

答案 1 :(得分:2)

尝试:

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

有关详细信息,请查看 7.2一章。在https://docs.python.org/2/tutorial/inputoutput.html

上阅读和编写文件