限制尝试只读取文件几次

Limit attempt read file only several times

我想对尝试打开文件但找不到文件时的尝试次数进行限制(比如三次)。

while True:
    inputfilename = input('Type the filename then press enter: ')
    try:
        inputfile  = open(inputfilename,"r", newline='')
    except FileNotFoundError:
        print ('File does not exist')
        print ('')
    else:
        break

上面代码的结果,没有限制。我怎样才能把限制放在上面的代码中。 我正在使用 python 3.5.

while True:替换为for _ in range(3):

_ 是一个变量名(也可以是 i)。按照约定,此名称意味着您有意不在下面的代码中使用此变量。它是一个 "throwaway" 变量。

range(python 2.7+ 中的xrange)是一个序列对象,它(懒惰地)生成一个介于 0 和作为参数给出的数字之间的序列。

如果你成功打开文件,在一个范围内循环三次:

for _ in range(3):
    inputfilename = input('Type the filename then press enter: ')
    try:
        inputfile  = open(inputfilename,"r", newline='')
        break
    except FileNotFoundError:
        print ('File does not exist')
        print ('')

或者放在一个函数中:

def try_open(tries):
    for _ in range(tries):
        inputfilename = input('Type the filename then press enter: ')
        try:
            inputfile = open(inputfilename, "r", newline='')
            return inputfile
        except FileNotFoundError:
            print('File does not exist')
            print('')
    return False


f =  try_open(3)
if f:
    with f:
        for line in f:
            print(line)

如果您想使用 while 循环,则以下代码有效。

count = 0
while count < 3:
    inputfilename = input('Type the filename then press enter: ')
    try:
        inputfile  = open(inputfilename,"r", newline='')
        count += 1
    except FileNotFoundError:
        print ('File does not exist')
        print ('')