文件不在目录中,用户重新输入文件名(循环)-Python



我想做的是使用它,这样当用户输入要打开的文件名然后读取时,如果在目录中找不到输入的文件,而不是在shell上出现错误消息,它应该要求用户再次输入文件名。

print("nEnter the name of the file you would like to encrypt, ensuring that you type .txt afterwards.")
filename = input()
try:
    sample=open(filename, 'r').read()
except IOError:
    print ("there is no such a file")

现在所有代码需要做的就是循环它,所以如果用户仍然没有输入要上传的文件所在的文件名,那么它应该要求用户重新输入他们想要上传的文件的名称。

顺便说一下,我只想上传文本文件。

感谢

您可以使用while:

while True:
    print("nEnter the name of the file you would like to encrypt, ensuring that you type .txt afterwards.")
    filename = raw_input()
    try:
        sample=open(filename, 'r').read()
        if sample:
            break
    except IOError:
        print ("there is no such a file, please try again")

最新更新