@curry_pan (yy kk)

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

一定時間ごとに保存されるデータをエクセルに記入したい

解決したいこと

watchdogで保存されたcsvデータを検出し、それを計算した結果をエクセルに記入させたいです。しかし、下図のようにひとつのファイルにつきデータが複数あり、かつ連続するデータのため一定時間ごと(例えば5秒ごと)に保存される仕組みです。このデータの計算結果をそれぞれA1,A2、、、と記入させていきたいです。
また、一定時間新たにデータが保存されなければエクセルデータを保存させたいです。保存先はこのデータらが保存されている同じ場所に指定したいです。
スクリーンショット 2023-01-17 191322.png

該当するソースコード

#ーーーwatchdogsでファイルを監視ーーー
import openpyxl
import time
import os

from watchdog.events import PatternMatchingEventHandler
from watchdog.observers import Observer

def exl_write(kekka, excel_filepath):
    time_start = time_now = time.time()
    line_num = 1
    wb = openpyxl.load_workbook('result.xltx')
    # シートを取得
    ws = wb.active
    # セルへ書き込む
    while True:
        if (time_now - time_start < 10):
            break      
        ws.cell(line_num,1).value = kekka
        
    # 保存する
    book.save(excel_filepath + 'data.xlsx')

class MyHandler(PatternMatchingEventHandler):
    def __init__(self, patterns):
        super(MyHandler, self).__init__(patterns=patterns)

    def on_created(self, event):
        filepath = event.src_path
        filename = os.path.basename(filepath)
        print(filename)
        
        kekka= test() #ここで計算を行う
        
        excel_filepath = file_path.removeprefix(filename)
        exl_write(kekka)


def watch(path):
    extensions = ["*.csv"]
    event_handler = MyHandler(extensions)
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

if __name__ == "__main__":
    path = os.path.dirname(os.path.abspath(__file__))
    watch(path)

結果

このプログラムですと、一個のデータをA1セルに記入して保存してしまう結果になります。行いたいことは上図ならばA1,A2,A3に結果をそれぞれ記入させたいのですがどのようにすればよいのでしょうか?

0 likes

No Answers yet.

Your answer might help someone💌