Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 写入文件会覆盖内容_Python_Python 3.x - Fatal编程技术网

Python 写入文件会覆盖内容

Python 写入文件会覆盖内容,python,python-3.x,Python,Python 3.x,因此,当我运行这段代码时,它工作得非常好,但它覆盖了秒表时间.txt中以前的时间因此,我到处搜索,但无法找到如何执行 #!/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

因此,当我运行这段代码时,它工作得非常好,但它覆盖了
秒表时间.txt中以前的时间
因此,我到处搜索,但
无法找到如何执行

#!/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))

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

with open('stopwatch_times.txt', 'a') as file_:
    ...  # Write to the file.
现在它将一个接一个地列出次。如果换行符有问题,请确保为系统添加正确的换行符。

尝试:

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

有关更多信息,请参阅第7.2章。在

读取和写入文件时,它会被覆盖,因为您打开了要覆盖的文件(
'w'
),而您只是在那里写入新的时间。它应该做什么?“寻求调试帮助的问题(“为什么这段代码不工作?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现该问题所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请参阅:如何创建最小、完整且可验证的示例。“当我删除('w')时,它会给我一个错误代码:回溯(最近一次调用最后一次):文件“C:\ProgramFiles(x86)\Python34\PROJECTS\Stopwatch\Stopwatch.py”,第14行,在文件\写入(秒表\时间)中io.UnsupportedOperation:不可写是的,我问程序应该做什么而不是覆盖文件。也许你想用
'a'
模式附加到文件的末尾?@Newbieprogrammer你还没有修改你的问题来说明我试图写的预期行为:打开('stopwatch\u times.txt','a'))作为文件,它是这样写的:0.500.100.541.65它是这样写的。我想这样写:0.50 0.10 0.54等等。好吧,格式化输出听起来像是一个新问题。@newbie程序员:时间字符串是这样运行的,因为它们前后都没有空格。所以要
文件,写(秒表时间+“”)
;或
文件写入(秒表时间+'\n')
将每个时间字符串放在一个单独的行上。克劳斯,如果文件是以文本模式打开的,则
'\n'
在写入时会自动转换为适合主机操作系统的行尾;相反,在读取文本文件时,本地行尾会转换为
'\n'
;Python会从C继承此行为。小心saying.另外,:)