如果找不到文件,Python脚本将中止

2024-09-27 19:24:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一名网络工程师,试图手工编写Cisco Event Manager小程序脚本是一件非常麻烦的事情,所以我拼凑了一个脚本,试图让它更容易/自动化

计划原因:

当您使用该程序时,它会将脚本输出到终端,并为您的记录创建一个文件。我创建了一个初始提示,询问您以前是否使用过该程序,以便它在开始之前完全擦除该文件。这样做的原因是为了消除数据混淆的任何可能性,并消除可能导致您尝试进行的配置更改出现问题的可能性

问题:

如果用户对最初的提示说“是”,询问他们以前是否使用过该程序,而Python无法找到该文件,则会出错

所需援助:

如果找不到文件,我想尝试让程序继续,而不是中止

(如果有人有任何关于清理的建议,也会很有帮助)

脚本:

# Used for creating, editing, erasing, reading files #
import os

# First While loop counter #
beg = 0
# Second While loop counter #
counter0 = 0
# Nested While loop counter #
counter1 = 0
# Used to start CLI action numbering at the correct point #
line = 3

# Searches for any previously made EMA script file and removes it. Currently errors out if file isn't seen #
while beg == 0:

    remove = input("Have you used this program before?\n[Y] Yes\n[N] No\n: ").lower()

    if remove == "y":
        os.remove("EMA_Script.txt")
        print("File Deleted")
        beg += 1

    elif remove == "n":
        beg += 1

    else:
        print("Incorrect input.")
        beg += 0

# Begins asking for CLI commands and writing inputs to file in sequence #
while counter0 == 0:

    name = input("\nName your applet: ")
    hour = int(input("\nAt what hour do you want this to run (24h clock)?: "))
    minute = int(input("\nAt what minute on the hour do you want this to run?: "))

    f = open("EMA_Script.txt", "a+")
    f.write('event manager applet {}\nevent time cron cron-entry "{} {} * * *"'.format(name, minute, hour))
    f.write('\naction 1.0 cli command "enable"\naction 2.0 cli command "conf t"')
    f.close()

    while counter1 == 0:
        print("\nBegin Command section.")
        action = input("\nCommand: ")
        forward = input("\nEnter 1 to add more or 2 if you are finished: ")

        if forward == "1":
            f = open("EMA_Script.txt", "a+")
            f.write('\naction {}.0 cli command "{}"'.format(line, action))
            f.close()
            line += 1
            counter1 += 0

        elif forward == "2":
            f = open("EMA_Script.txt", "a+")
            f.write('\naction {}.0 cli command "{}"'.format(line, action))
            f.close()
            line += 1
            f = open("EMA_Script.txt", "a+")
            f.write('\naction {}.0 cli command "end"'.format(line))
            f.close()
            f = open('EMA_Script.txt', 'r')
            print(f.read())
            f.close()
            counter1 += 1

        else:
            print("Incorrect input. Re-input previous command!")
            counter1 += 0

    break

Tags: to程序txtinputclilinescriptopen
3条回答

我知道如果您的文件不存在并且用户键入“y”,就会出现问题。在这种情况下,您的函数应该如下所示:

# Searches for any previously made EMA script file and removes it. Currently errors out if file isn't seen #
while beg == 0:

    remove = input("Have you used this program before?\n[Y] Yes\n[N] No\n: ").lower()

    if remove == "y":
        # This line will check if the file exists, if it does it will be deleted
        if os.path.exists("EMA_Script.txt"):
            os.remove("EMA_Script.txt")
            print("File Deleted")
        beg += 1

    elif remove == "n":
        beg += 1

    else:
        print("Incorrect input.")
        beg += 0

如您所见,我添加了os.path.exists("EMA_Script.txt"),这将帮助您了解该文件是否存在,如果存在,则将其删除。如果文件不存在,它将继续执行下一条指令beg += 1,从而从循环中中断

让我知道这是否对你有效

open的默认行为是在文件不存在时引发异常。如果要执行其他操作,则需要捕获异常:

try:
    f = open("EMA_Script.txt", "a+")
except FileNotFoundError:
    # your code to handle the case when the file doesn't exist (maybe open with write mode)

尽管我们在这里,但在处理文件时使用上下文是一种很好的做法,以确保它们始终处于关闭状态——事实上,任何需要关闭的文件(如数据库连接)都应该这样做。原因是,即使在openclose之间发生异常,上下文也会确保文件已关闭

因此,与此模式不同:

f = open(...)
# do things with file
f.close()

您要执行以下操作:

with open(...) as f:
    # do things with file

您可以使用try/except block捕捉FileNotFoundError。此外,使用break而不是beg变量将清理代码:

import os

while True:
    remove = input("Have you used this program before?\n[Y] Yes\n[N] No\n: ").lower()
    if remove == "y":
        try:
            os.remove("EMA_Script.txt")
            print("File Deleted")
        except FileNotFoundError:
            pass
        break
    elif remove == "n":
        break
    else:
        print("Incorrect input.")

第二个(嵌套的)循环也是如此:如果输入正确,则中断循环,否则继续循环

相关问题 更多 >

    热门问题