下面是一些用来打开CSV文件的代码。其值存储如下:
03/05/2017 09:40:19,21.2,35.0
03/05/2017 09:40:27,21.2,35.0
03/05/2017 09:40:38,21.1,35.0
03/05/2017 09:40:48,21.1,35.0
这只是我在实时打印程序中使用的一段代码,它完全可以工作,但是数组变得如此庞大这一事实是不干净的。通常情况下,当程序运行且数组的长度非常大时,新值会添加到CSV中。有没有办法避免这样的爆炸阵列? 只要运行程序,你将不得不作出一个CSV与这些值太,你会看到我的问题
from datetime import datetime
import time
y = [] #temperature
t = [] #time object
h = [] #humidity
def readfile():
readFile = open('document.csv', 'r')
sepFile = readFile.read().split('\n')
readFile.close()
for idx, plotPair in enumerate(sepFile):
if plotPair in '. ':
# skip. or space
continue
if idx > 1: # to skip the first line
xAndY = plotPair.split(',')
time_string = xAndY[0]
time_string1 = datetime.strptime(time_string, '%d/%m/%Y %H:%M:%S')
t.append(time_string1)
y.append(float(xAndY[1]))
h.append(float(xAndY[2]))
print([y])
while True:
readfile()
time.sleep(2)
这是我得到的结果:
[[21.1]]
[[21.1, 21.1]]
[[21.1, 21.1, 21.1]]
[[21.1, 21.1, 21.1, 21.1]]
[[21.1, 21.1, 21.1, 21.1, 21.1]]
感谢您的帮助
如果还想限制要保留的条目总数,可以使用Python的^{} 。它生成一个具有最大长度的列表。一旦列表已满,任何新条目都会将最旧的条目推离开始
您的列表不断增长的原因是,在继续添加新条目之前,您需要重新读取文件,直到最后一个条目为止。假设您的时间戳是唯一的,您可以使用
takewhile()
来帮助您做到这一点,即读取条目直到满足条件另外,使用Python内置的^{} 库来将每个值读入每一行的列表中,使用这些条目也更容易。因为您有一个标题行,所以在开始循环之前,请使用
next()
阅读本文相关问题 更多 >
编程相关推荐