当从CSV向数组添加值时,数组的长度会爆炸

2024-04-19 09:27:13 发布

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

下面是一些用来打开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]]

感谢您的帮助


Tags: csv代码import程序datetimetime数组split
1条回答
网友
1楼 · 发布于 2024-04-19 09:27:13

如果还想限制要保留的条目总数,可以使用Python的^{}。它生成一个具有最大长度的列表。一旦列表已满,任何新条目都会将最旧的条目推离开始

您的列表不断增长的原因是,在继续添加新条目之前,您需要重新读取文件,直到最后一个条目为止。假设您的时间戳是唯一的,您可以使用takewhile()来帮助您做到这一点,即读取条目直到满足条件

from itertools import takewhile    
from collections import deque
from datetime import datetime
import csv
import time


max_length = 1000     # keep this many entries

t = deque(maxlen=max_length) # time object
y = deque(maxlen=max_length) # temperature
h = deque(maxlen=max_length) # humidity

def read_file():
    with open('document.csv', newline='') as f_input:
        csv_input = csv.reader(f_input)
        header = next(csv_input)    # skip over the header line

        # If there are existing entries, read until the last read item is found again
        if len(t):
            list(takewhile(lambda row: datetime.strptime(row[0], '%d/%m/%Y %H:%M:%S') != t[-1], csv_input))

        for row in csv_input:
            print(row)
            t.append(datetime.strptime(row[0], '%d/%m/%Y %H:%M:%S'))
            y.append(float(row[1]))
            h.append(float(row[2]))

while True:
    read_file()
    print(t)
    time.sleep(1)

另外,使用Python内置的^{}库来将每个值读入每一行的列表中,使用这些条目也更容易。因为您有一个标题行,所以在开始循环之前,请使用next()阅读本文

相关问题 更多 >