2017-05-04 2 views
0

에서 값을 추가 할 때 배열의 길이가 폭발하면 CSV 파일을 여는 코드가 작성됩니다. 그 값은 다음과 같이 저장됩니다아래 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를 만들어야하며 내 문제가 나타납니다. 어떤 도움에 감사드립니다

[[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]] 

:

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) 

내가 얻을 출력됩니다.

+1

maxs.length와 함께 collections.deque를 사용하여 데이터를 추가 할 수 있습니다. – Hackaholic

+0

잠시만 기다려주세요. readFile 메서드 내에서 목록을 선언하거나 추가 대신 insert를 사용할 수 있습니다. – papey

답변

0

보관하려는 총 항목 수를 제한하려면 Python의 deque을 사용할 수 있습니다. 최대 길이를 특징으로하는 목록을 생성합니다. 목록이 가득 차면 새로운 항목이 가장 오래된 항목을 처음부터 밀어냅니다.

귀하의 목록이 커지는 이유는 새 항목을 계속 추가하기 전에 마지막 항목까지 파일을 다시 읽어야하기 때문입니다. 타임 스탬프가 고유하다고 가정하면 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) 

또한, 사용 항목과 작업하는 것이 더 쉽습니다 파이썬의 각 행에 대해 목록에 각각의 값을 읽을 수 csv 라이브러리에 내장. 머리글 행을 가지고 있으므로 루프를 시작하기 전에 next()을 사용하여 읽으십시오.