简体   繁体   English

每次迭代函数时都要写到新行?

[英]Writing to a new line every time a function is iterated?

I'm just having a little trouble with text files and how I would write to a new line to create a list every time a function is called. 我在处理文本文件时有点麻烦,并且每次调用函数时如何写新行以创建列表。

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

I would like to write to a new line of the text file everytime this is passed and the function is called. 我想在每次传递文本并调用函数时写入文本文件的新行。

Use a to append, if you have a loop you should also open the file outside it: 使用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+ opens for reading and writing so the pointer is going to be at the start of the file when you open it therefore will write to the first line not append to it. r+打开以进行读取和写入,因此打开时指针将位于文件的开头,因此将写入第一行而不附加到文件的第一行。

If the function is repeatedly calling itself you may be better off using a while loop. 如果函数反复调用自身,则使用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("-----------------------------------------------------------------------------------------------------------")

Maybe adding a time.sleep in between checks. 也许在time.sleep检查之间增加了time.sleep

You can open the file only once and close it when you're program exits. 您只能打开该文件一次,然后在程序退出时将其关闭。 Just add a "\\n" to the end of your f.write line. 只需在f.write行的末尾添加“ \\ n”即可。 If you need the file to be flushed (so that output appears immediately) you can specify zero buffering: 如果需要刷新文件(以便立即显示输出),则可以指定零缓冲:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM