每次迭代函数时写入新行?

时间:2015-02-11 12:37:43

标签: python list file function

我只是对文本文件有点麻烦,以及每次调用函数时如何写入新行来创建列表。

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()

我希望每次传递文本文件的新行并调用该函数。

2 个答案:

答案 0 :(得分:1)

使用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循环。

with  open('Camera Output.txt', 'a') as f:
    while True:
        # rest of code 
        if speedCarMph > 60:
                f.write("{} was travelling at {}MPH at {} and has broken the law".format(licensePlate, speedCarMph, camInput2) + "\n")
                f.write("-----------------------------------------------------------------------------------------------------------")

可能在两次检查之间添加time.sleep

答案 1 :(得分:0)

您只能打开一次文件,并在程序退出时将其关闭。只需在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()