【发布时间】:2021-03-01 08:45:42
【问题描述】:
目前我正在编写一个包含 2 个单独文件 Main.py 和 App.py 的程序,Main.py 读取距离和温度等读数,并将其写入名为 data.txt 和 App.py 的文件中,然后从文本文件。
#main.py
def scan():
global object_temp, close_enough, real_distance #close enough writes true is someone is near
while True:
f=open("data.txt","a+")
a=str(scan())+"\n"
f.write(a):
log.log(a)
f.close()
#data.txt
#imagine this but with almost 60000 line each time I run it as it's printing every second
[26.03, 30.91, 126.5, False]
[25.97, 30.89, 125.69, False]
[25.97, 30.89, 124.74, False]
.
.
etc
#app.py
def getValues():
global prevValues
f=open("data.txt","r")
latestValue = str(f.read())
f.close()
#log.log(latestValue,"LATEST VALUES")
latestValue = latestValue.split("\n")[-2].strip('][').split(', ')
log.log(latestValue,"LATEST VALUES")
if latestValue=="":
return(prevValues)
else:
return(latestValue)
prevValues=latestValue
现在的问题是文本文件被读数淹没,随着时间的推移会减慢程序的速度,我知道这不是最有效的方法,但我刚刚进入 python,所以有吗无论如何将数据直接从 Main.py 传输到 App.py 或在达到一定行数后删除文本文件读取的方法?例如 50 行后它开始删除/覆盖这些行?
【问题讨论】:
-
也许使用合适的数据库?
-
您可能想查看 asyncio (docs.python.org/3/library/asyncio.html#module-asyncio),您会发现它旨在满足您的需求。
标签: python