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

File not in directory, user re-enters file name (loop) - 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")