12

I tried a try: catch but it isn't working. I suppose I could change it to an if statement but don't understand why this isn't working. This is my very first "real" project. I'm building an irrigation controller and creating a dictionary of schedules for irrigation. The first is the code I have so far and the second code is the "test" by itself that I'm trying. Every time I run the code it rewrites over the existing file, when what I want is for it to open the file if it already exists and NOT write it again.

# timer will first look for a saved file(dictionary) of already recorded
# irrigation times.  If no file exists it will create one.  

# irrigation timer which does scheduled irrigation as well as cyclic   irrigation for propagating plants.
# uses a lcd 1602 display
# will use up to 10 different valves

import time
import datetime
import threading
import RPi.GPIO as GPIO
from RPLCD import CharLCD # http://www.circuitbasics.com/raspberry-pi-lcd-set-up-and-programming-in-python/

GPIO.setmode(GPIO.BOARD)

# pinouts for lcd pins
lcd = CharLCD (cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[33, 31, 29, 23]) 

# valve pins
valve_1 = 8
valve_2 = 10
valve_3 = 12
valve_4 = 16
valve_5 = 18
valve_6 = 22
valve_7 = 24
valve_8 = 26
valve_9 = 32
valve_10 = 36

# setup valve pins as outputs
GPIO.setup(valve_pin1, GPIO.OUT)
GPIO.setup(valve_pin2, GPIO.OUT)
GPIO.setup(valve_pin3, GPIO.OUT)
GPIO.setup(valve_pin4, GPIO.OUT)
GPIO.setup(valve_pin5, GPIO.OUT)
GPIO.setup(valve_pin6, GPIO.OUT)
GPIO.setup(valve_pin7, GPIO.OUT)
GPIO.setup(valve_pin8, GPIO.OUT)
GPIO.setup(valve_pin9, GPIO.OUT)
GPIO.setup(valve_pin10, GPIO.OUT)

#set all valve pins to off
GPIO.output(valve_pin1, False)
GPIO.output(valve_pin2, False)
GPIO.output(valve_pin3, False)
GPIO.output(valve_pin4, False)
GPIO.output(valve_pin5, False)
GPIO.output(valve_pin6, False)
GPIO.output(valve_pin7, False)
GPIO.output(valve_pin8, False)
GPIO.output(valve_pin9, False)
GPIO.output(valve_pin10, False)

# check to see if a schedule has been saved
def sched_check()
    try:
        file = open("schedule.dat", "r")
        schedule = schedule.read()
        file.close()
    # create a list of schedule dictionaries
    except:
        schedule_list = []
        for schedule_number in range(10):
            schedule = {
                                        "timed" : {
                                                  "watering_days" : [],
                                                  "watering_times" : [],
                                                  "duration" : "timed_duration",
                                                  },
                                        "cyclic" : {
                                                  "time_on" : "seconds_on",
                                                  "time_off" : "seconds_off",
                                                  "blackout_window_start" : "blkout_time_start",
                                                  "blackout_window_stop" : "blkout_time_stop",
                                                   },
                                        }
            schedule_list.append(schedule)
        file = open("schedule.dat", "w")
        file.write(str(schedule_list))
        file.close()

And this is the problem area by itself.

def sched_check():
    try:
        file = open("schedule.dat", "r")
        schedule = schedule.read()
        file.close()
        print("file already exists")
    # create a list of schedule dictionaries
    except:
        schedule_list = []
        for schedule_number in range(10):
            schedule = {
                                        "timed" : {
                                                  "watering_days" : [],
                                                  "watering_times" : [],
                                                  "duration" : "timed_duration",
                                                  },
                                        "cyclic" : {
                                                  "time_on" : "seconds_on",
                                                  "time_off" : "seconds_off",
                                                  "blackout_window_start" : "blkout_time_start",
                                                  "blackout_window_stop" : "blkout_time_stop",
                                                   },
                                        }
            schedule_list.append(schedule)
        file = open("schedule.dat", "w")
        file.write(str(schedule_list))
        file.close()
        print("new file created")

sched_check()
cs95
  • 379,657
  • 97
  • 704
  • 746
Nathan Rigg
  • 141
  • 1
  • 6
  • I think `schedule = schedule.read()` is supposed to be `schedule = file.read()` – jacoblaw Jun 19 '17 at 21:03
  • When you say open the file and don't write it again, you mean you're trying to append data to the end of the file ? or do nothing ? If you want to append data you could use `a` flag instead of `w` and check if the file exist or not. – Chiheb Nexus Jun 19 '17 at 21:04
  • Note that from the answers in the dup reference, the one with `open(..., 'x')` is probably the one you want. This causes `open()` to croak with `FileExistsError` when the file to open already exists. And it's the only one that's not racy ;-). – dhke Jun 19 '17 at 21:10

1 Answers1

5

You can use os.path.exists("schedule.dat"). It returns a boolean result.

An alternative solution using os.stat involves:

import os
try:
    os.stat("schedule.dat")
    ... # file exists
except:
    file = open("schedule.dat", "w")
    ...

An exception is raised is you try to stat a non-existent file.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • Thank you all. My problem was schedule.ready() was supposed to be file.read(). Dumb mistake on my part. Thanks jacoblaw and I will look into that Chiheb Nexus and coldpeed as an alternative way of doing it. – Nathan Rigg Jun 19 '17 at 21:12