python - 发生错误时更改变量而不终止程序

标签 python python-3.x

这是我的基本代码:

fname = input("What is the name of the file to be opened")
    file = open(fname+".txt", "r")
    message = str(file.read())
    file.close()

我想做的本质上是确保程序尝试打开的文件存在,我想知道是否可以编写尝试打开该文件的代码,当它发现该文件不存在时告诉用户输入有效的文件名而不是终止显示错误的程序。

我在想是否有什么东西可以检查代码是否返回错误,如果确实返回错误,则可能会使变量等于无效,然后 if 语句会读取告诉用户问题,然后再要求用户输入另一个文件名。

伪代码:

fname = input("What is the name of the file to be opened")
        file = open(fname+".txt", "r")
        message = str(file.read())
        file.close()
if fname returns an error:
    Valid = invalid
while valid == invalid:
    print("Please enter a valid file name")
    fname = input("What is the name of the file to be opened")

if fname returns an error:
    Valid = invalid

等等

最佳答案

我想这个想法是你想要循环直到用户输入有效的文件名。试试这个:

import os

def get_file_name():
    fname = input('Please enter a file name: ')
    if not os.path.isfile(fname+".txt"):
      print('Sorry ', fname, '.txt is not a valid filename')
      get_file_name()
    else:
      return fname

file_name = get_file_name()

关于python - 发生错误时更改变量而不终止程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33406511/

相关文章:

python - 如何按顺序连接字符串?

python - 在具有显式键值的对象列表中查找元素

python - pyplot 图例用于按值着色的散点图

python - python 中现有 dict 列表中的 dict 列表

python - 理解 time.clock() 和 time.time()

python - 更新最新 PySide 后 Pyinstaller 错误

python - Pandas:通过拆分列和变量中的列来 reshape 数据框

python - 无法在 django 1.8 中使用自定义用户模型创建 super 用户

listview - 如何上下移动多个ListStore元素

python - 获取调用方法的对象