Python 限制仅多次尝试读取文件
我想对尝试打开文件但找不到文件时的尝试次数进行限制(比如三次)Python 限制仅多次尝试读取文件,python,python-3.5,Python,Python 3.5,我想对尝试打开文件但找不到文件时的尝试次数进行限制(比如三次) while True: inputfilename = input('Type the filename then press enter: ') try: inputfile = open(inputfilename,"r", newline='') except FileNotFoundError: print ('File does not exist')
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
以上代码的结果没有限制。如何在上述代码中设置限制。
我正在使用Python3.5。替换
,而True:
由替换范围(3):
是一个变量名(也可以通过i
实现)。按照惯例,此名称表示您有意不在下面的代码中使用此变量。这是一个“一次性”变量
range
(xrange
在python 2.7+中)是一个序列对象,它(延迟地)生成一个介于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 ('')
count=0
当计数小于3时:
inputfilename=input('键入文件名,然后按enter:')
尝试:
inputfile=open(inputfilename,“r”,换行符=“”)
计数+=1
除FileNotFoundError外:
打印('文件不存在')
打印(“”)
yes抱歉,Python3中的范围替换为范围。修正我的答案