再次尝试使用try和except打开文件

时间:2019-02-14 15:14:41

标签: python python-3.x

open_file():此函数不带参数,然后使用try-except格式提示输入文件名,打开数据文件,如果成功则返回文件指针。您的函数应该能够捕获错误并在打开失败时显示错误消息;然后再提示。它将提示

我已经编写了此代码,但是不确定它是否正确并满足上述要求。谁能帮我吗?

react-native-tab-view

3 个答案:

答案 0 :(得分:0)

def open_file(max_tries=20):
    tries = 0
    fp = None    # We don't have that yet
    while not tries or not fp:  # While the file is not loaded (or we haven't tried)
        tries += 1 # One more try
        try:       # Try to load it
            fp = open(input("enter a filename : "))
        except FileNotFoundError:   # Oops  
            print("file not found")  # We should tell the user about that
            if tries > max_tries: break  # We shouldn't go into an infinite loop
        except IsADirectoryError:   # Oops  
            print("file is a directory")  # We should tell the user about that
            if tries > max_tries: break  # We shouldn't go into an infinite loop
    else: return fp      # When you got the fp, return it
    pass # If you didn't get it run the code here (maybe raise an exception)
    # If you don't raise an exception, it will return None

答案 1 :(得分:0)

看起来像一个作业,所以我不会发布完整的解决方案,但是我至少可以回答明确的问题:您的代码显然不符合要求-如果该代码不提示输入其他文件名找不到第一个-不会显示任何错误-现在,它执行了不仅不需要而且完全意外的操作-如果找不到要求的文件,它将尝试打开一些硬编码的文件名。

只是一个提示:重复操作通常是使用forwhile循环完成的。

答案 2 :(得分:-1)

我做了一些重做,但这会按照您想要的去做。

def open_file():
    try:
        file_name = input("What is the filename? ")
        with open(file_name) as fp:
            new_doc = fp.read()
        return new_doc
    except FileNotFoundError:
        print("File not found")
        new_doc = open_file()
        return new_doc


file = open_file()
print(file)