Search code examples
pythondatetimetimepython-datetime

Is there any way to store data every 5 second in new text file?


I have created a program which is reading the sensor data. As per my usecase i have to store the readings in a text file every 5 seconds with new file names example: file1, file2, file3 and so on until i stop the program using keyboard. Can anyone guide me to accomplish this task?

import sys
import time
import board
import digitalio
import busio
import csv
import adafruit_lis3dh
from datetime import datetime, timezone
i2c = busio.I2C(board.SCL, board.SDA)
int1 = digitalio.DigitalInOut(board.D6)  # Set this to the correct pin for the interrupt!
lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c, int1=int1)
lis3dh.range = adafruit_lis3dh.RANGE_2_G



with open("/media/pi/D427-7B2E/test.txt", 'w') as f:
  sys.stdout = f


  while True:
      ti = int(datetime.now(tz=timezone.utc).timestamp() * 1000)
      x, y, z = lis3dh.acceleration
      print('{}, {}, {}, {}'.format(ti,x / 9.806, y / 9.806, z / 9.806))
      time.sleep(0.001)
      pass

Solution

  • can you try logging? have a look on TimedRotatingFileHandler may be this could help

    Can you look into threading.Timer as recursive and set timer as you wish and call the function at program start there you can either update the file name in array/dict so that it will be reflected to rest of program or you can write the contents of the array into file and empty the array.

         def write_it():
            threading.Timer(300, write_it).start()
    
         write_it()