用户inpu的Python FileNotFoundError

2024-09-29 21:23:27 发布

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

我正在做一个程序,把文件的内容加密成密文。我的问题是,当我的程序要求用户输入他们想要加载的文件名,而用户没有给出有效的响应时,就会出现“FileNotFoundError:”。我希望我的程序有一个功能,如果用户没有给出有效的响应,程序将继续告诉用户重试。在

def EncryptCode():
    encryptFileLoad = input("Name the file and directory you want to load with the ending '.txt':\n") 
    with open (encryptFileLoad,mode="r",encoding="utf=8") as encrypt_file:
        encryptFile = encrypt_file.read()

我得到这样一个错误:

^{pr2}$

我试过这样做:

def EncryptCode():
    ...
    try:
        ...
    except FileNotFoundError:
        return EncryptCode

Tags: 文件the用户程序功能内容文件名def
2条回答

怎么办

def EncryptCode():
    file_not_found = True
    while(file_not_found):
        try:
            encryptFileLoad = input("Name the file and directory you want to load with the ending '.txt':\n")
            file_not_found = False
        except FileNotFoundError:
            print('that didnt work! try again')
    with open (encryptFileLoad,mode="r",encoding="utf=8") as encrypt_file:
        encryptFile = encrypt_file.read()

你差点就成功了。检查http://www.python-course.eu/recursive_functions.php应该是这样的:

def EncryptCode():
    try:
        encryptFileLoad = input("Name the file and directory you want to load with the ending '.txt':\n")
        with open(encryptFileLoad,mode="r",encoding="utf=8") as encrypt_file:
            encryptFile = encrypt_file.read()
            return encryptFile
    except FileNotFoundError:
        print('File not found. Input correct filename')
        return EncryptCode()

或者您可以使用while循环来要求用户输入正确的文件名,例如:

^{pr2}$

相关问题 更多 >

    热门问题