在Python中逐秒保存结果

2024-04-30 06:25:01 发布

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

I am measuring a parameter which is a distance between two objects in a live video. I want to save my results (distance) in a text file "second by second" along with the time. To be more specific I want a text file

包括两列:

1- Time = [1,2,3,4,5,6,...]

2- Distance = [7,4,8,2,3,1,...]

我需要这个文本文件一秒一秒的更新。我想知道有没有人能帮我。你知道吗

谢谢!你知道吗


Tags: textinlivewhichobjectsparameterisbetween
1条回答
网友
1楼 · 发布于 2024-04-30 06:25:01

给你举个例子,不完全是你想要的,但也许有用:

#!/usr/bin/env python3.6
import time
from datetime import datetime
from pathlib import Path

fname = "a.txt"


def get_distance():
    from random import randint

    return randint(1, 10000)


def main():
    t = 1
    p = Path(fname)
    if not p.exists():
        s = " Time Distance"
        p.write_text(f"{s}\n")
        print(f"``{s}`` appended to {fname}")
    with p.open("a") as f:
        while True:
            d = get_distance()
            line = f"{t:5} {d}"
            f.write(f"{line}\n")
            print(f"``{line}`` appended to {fname}")
            time.sleep(1)
            t += 1


if __name__ == "__main__":
    main()

输出(a.txt):

 Time Distance
    1 5772
    2 7654
    3 2918
    4 3980

相关问题 更多 >