Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Writing to File Issue
#1
Hello,

I've got this python program written that uses a 16x1 multiplexer with 16 sensors and takes the readings from each channel. This part of the program works fine. The two issues I'm having are:

1. I'm trying to write to a file the results of my readings. The way I have the file write set up is I create a file with the date and time at the time of starting the program in order to have unique file names. I ran the program and initially the file writing was working fine but then I quit the program and ran the program again to test it. It created the unique file with the data and time in the name, however the file was blank even though it was the same code being used.

2. I'm using a try and exceptKeyboardInterrupt and in the except part I have it to write the final results of each of my readings. However on the first attempt of running the program where it did write to the file, the part to be written in during the except was missing.

Any help with this would be appreciated.

import RPi.GPIO as GPIO
import time
from datetime import date

GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
   
GPIO.setup(11, GPIO.OUT) #s0
GPIO.setup(13, GPIO.OUT) #s1
GPIO.setup(15, GPIO.OUT) #s2
GPIO.setup(16, GPIO.OUT) #s3
GPIO.setup(22, GPIO.OUT) #enable
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)  #Signal Input

s0 = [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1] #s0 values
s1 = [0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1] #s1 values
s2 = [0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1] #s2 values
s3 = [0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1] #s3 values

GPIO.output(22,GPIO.LOW)

def s0_pin(x,y):
    GPIO.output(x,y)

def s1_pin(x,y):
    GPIO.output(x,y)
    
def s2_pin(x,y):
    GPIO.output(x,y)

def s3_pin(x,y):
    GPIO.output(x,y)

def current_readings():
    signal_reading = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
    times = []
    for i in range(16): 
        s0_pin(11,s0[i])
        s1_pin(13,s1[i])
        s2_pin(15,s2[i])
        s3_pin(16,s3[i])
        t = time.localtime()
        current_time = time.strftime("%H:%M:%S", t)
        times.append(current_time)
        if GPIO.input(18):
            signal_reading[i] = 0
        else:
            signal_reading[i] = 1
    return signal_reading, times

def previous_readings(readings_list):
    old_readings.append(readings_list)
    if len(old_readings) > 5:
        old_readings.pop(0)
    return old_readings

def previous_times(times_list):
    old_times.append(times_list)
    if len(old_times) > 5:
        old_times.pop(0)
    return old_times

cage_totals = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

try:
    today = date.today()
    today_now = str(today)
    now = time.localtime()
    time_now = time.strftime("%H:%M:%S", now)
    results = open("MCRs"+today_now+"_"+time_now+".txt", "a+")
    results.write("Mouse Cage Reading results for: " + today_now + "(Year/Month/Day)\n")
    results.write("This file displays and records information on mouse movement for cages who return a 1 (i.e. the mouse set off the sensor) on a predefined time interval (currently 5 seconds)\n")
    results.write("Total mouse movements will be displayed as a running total at the end of this file for each cage\n")
    while True:
        old_readings = []
        old_times = []
        present_readings, present_time = current_readings()
        results.write("\n")
        results.write("Cage     Movement     Time\n")
        print("Multiplexer readings: ")
        print("----------------------")
        for i in range(16):
          print(i," = ", s0[i],s1[i],s2[i],s3[i],"Reading: ",present_readings[i], " at time: ", present_time[i])
          cage_totals[i] = cage_totals[i] + present_readings[i]
          if present_readings[i] == 1:
              results.write(str(i) + "   " + str(present_readings[i]) + "   " + str(present_time[i])+"\n")
        print("-----------------------")
        results.write("\n")
        time.sleep(5)
        old_readings = previous_readings(present_readings)
        old_times = previous_times(present_time)
        print()
        print("Here are the previous readings: ", old_readings)
        print("Here are the previous times: ", old_times)
except KeyboardInterrupt:
    results.write("\n")
    results.write("Here are the cage totals for the run-time of this experiment\n")
    results.write("Cage     # of times moved\n")
    for i in range(16):
        results.write(str(i) + "    " + str(cage_totals[i])+"\n")
    results.close()
    GPIO.cleanup()
Reply
#2
You could perhaps use a try:... finally: .... The finally part is normally always executed.
Reply
#3
(Jun-04-2020, 09:13 PM)Gribouillis Wrote: You could perhaps use a try:... finally: .... The finally part is normally always executed.

How would I go about solving the first problem though?
Reply
#4
I don't understand what you mean by the file is blank. Doesn't it contain the first sentence Mouse Cage Reading results for: ... ?

You could perhaps add a few print() statements in the program to see which lines get executed.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Issue in writing sql data into csv for decimal value to scientific notation mg24 8 2,882 Dec-06-2022, 11:09 AM
Last Post: mg24
  Writing string to file results in one character per line RB76SFJPsJJDu3bMnwYM 4 1,309 Sep-27-2022, 01:38 PM
Last Post: buran
  Writing to json file ebolisa 1 970 Jul-17-2022, 04:51 PM
Last Post: deanhystad
  Delimiter issue with a CSV file jehoshua 1 1,220 Apr-19-2022, 01:28 AM
Last Post: jehoshua
  File handling issue GiggsB 4 1,393 Mar-31-2022, 09:35 PM
Last Post: GiggsB
  Writing to External File DaveG 9 2,411 Mar-30-2022, 06:25 AM
Last Post: bowlofred
  How can I solve this file handling issue? GiggsB 17 3,423 Feb-14-2022, 04:37 AM
Last Post: GiggsB
  How to solve this file handling issue? GiggsB 3 1,633 Jan-10-2022, 09:36 AM
Last Post: Gribouillis
  Writing to file ends incorrectly project_science 4 2,642 Jan-06-2021, 06:39 PM
Last Post: bowlofred
  Writing unit test results into a text file ateestructural 3 4,654 Nov-15-2020, 05:41 PM
Last Post: ateestructural

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020