每次迭代一个函数时都写一个新行?

2024-09-28 05:27:17 发布

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

我只是在处理文本文件和如何在每次调用函数时写入一个新行来创建一个列表有点麻烦。在

if speedCarMph > 60:
        f = open('Camera Output.txt', 'r+')
        f.write("{} was travelling at {}MPH at {} and has broken the law".format(licensePlate, speedCarMph, camInput2) + "\n")
        f.write("-----------------------------------------------------------------------------------------------------------")
        f.close()
        DeltaTimeGen()
    else:
        DeltaTimeGen()

我想在每次传递这个函数和调用函数时都写入文本文件的新行。在


Tags: txt列表outputifopenatwritecamera
2条回答

使用a进行追加,如果有循环,还应在循环之外打开文件:

with open('Camera Output.txt', 'a') as f: # with closes your file
    if speedCarMph > 60:              
            f.write("{} was travelling at {}MPH at {} and has broken the law".format(licensePlate, speedCarMph, camInput2) + "\n")
            f.write("                                                     -\n")
    DeltaTimeGen() # if/else is redundant

r+打开进行读写操作,因此当您打开文件时,指针将位于文件的开头,因此将写入第一行而不是附加到该行。在

如果函数反复调用自己,那么最好使用while循环。在

^{pr2}$

也许在检查之间加一个time.sleep。在

您只能打开一次文件,并在程序退出时将其关闭。只需在f.write行的末尾添加一个“\n”。如果需要刷新文件(以便立即显示输出),可以指定零缓冲:

bufsize = 0
f = open('Camera Output.txt', 'r+', bufsize)

if speedCarMph > 60:
        f.write("{} was travelling at {}MPH at {} and has broken the law".format(licensePlate, speedCarMph, camInput2) + "\n")
        f.write("                                                     -\n")
        DeltaTimeGen()
    else:
        DeltaTimeGen()

f.close()

相关问题 更多 >

    热门问题