【问题标题】:Check to see if a file exists, and create it if it doesn't [duplicate]检查文件是否存在,如果不存在则创建它[重复]
【发布时间】:2017-11-22 05:14:23
【问题描述】:

我尝试了 try: catch 但它不起作用。我想我可以将其更改为 if 语句,但不明白为什么这不起作用。这是我的第一个“真正的”项目。我正在构建一个灌溉控制器并创建一个灌溉时间表字典。第一个是我到目前为止的代码,第二个代码是我正在尝试的“测试”本身。每次我运行它重写现有文件的代码时,当我想要它打开文件时,如果它已经存在并且不再写入它。

# 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()

这本身就是问题所在。

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()

【问题讨论】:

  • 我认为schedule = schedule.read() 应该是schedule = file.read()
  • 当您说打开文件并且不再写入时,您的意思是您正在尝试将数据附加到文件末尾?还是什么都不做?如果要附加数据,可以使用a 标志而不是w 并检查文件是否存在。
  • 请注意,从 dup 参考中的答案中,open(..., 'x') 的答案可能是您想要的答案。当要打开的文件已经存在时,这会导致open()FileExistsError 一起发出嘶嘶声。而且它是唯一不活泼的 ;-)。

标签: python python-3.x raspberry-pi raspberry-pi3


【解决方案1】:

您可以使用os.path.exists("schedule.dat")。它返回一个布尔结果。

使用os.stat 的替代解决方案包括:

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

如果您尝试stat 一个不存在的文件,则会引发异常。

【讨论】:

  • 谢谢大家。我的问题是 schedule.ready() 应该是 file.read()。我的愚蠢错误。感谢 jacoblaw,我将研究 Chiheb Nexus 和 Coldpeed 作为替代方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-06
  • 2011-09-15
  • 1970-01-01
  • 2019-08-08
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
相关资源
最近更新 更多