我试图写一个程序,要求一个特定的文件名,然后处理输入的文件名,使之成为一个列表。限制是用户只有三次机会键入正确的文件名。这是我的密码:
import os.path
def file_name_tries():
for i in range(3):
filename = input('please enter filename: ')
try:
infile = open(filename,'r')
# Do whatever you want, e.g.
#print infile.read()
return infile
exit()
except IOError:
if not os.path.exists(filename): print ('File does not exist')
else: print ('Error opening file')
print ('you have exceed your three tries' )
def process_file():
#file_name=input('file name: ')
#input_file=open(file_name,'r')
input_file=file_name_tries()
input_list=[]
#for loop strips each line of end characters
#and splits each line of the input file at ; and turns the line to a list
for line in input_file:
line_list=line.strip().split(';')
#appends each line_list to input_list
input_list.append(line_list)
print( input_list)
process_file()
错误:
please enter filename: mlb.txt
please enter filename: mlb.txt
please enter filename: mlb.txt
File does not exist
you have exceed your three tries
Traceback (most recent call last):
File "C:\Users\Dasinator\Documents\Books IX\Python Examples\textbook examples\project 07\passwordenter3times.py", line 29, in <module>
open_file()
File "C:\Users\Dasinator\Documents\Books IX\Python Examples\textbook examples\project 07\passwordenter3times.py", line 24, in open_file
for line in input_file:
TypeError: 'NoneType' object is not iterable
如有任何建议,我将不胜感激。谢谢
只要在用户成功时用
return file_open
替换您的break
(并删除底部的返回,这是导致错误的原因)。你知道吗如果用户失败了三次,那么函数将返回None。你知道吗
另存为
test.py
:以下是它在终端上的工作原理:
要“功能化”最多三次尝试打开文件,请尝试:
终端上:
如果您不希望程序在超过三次尝试后结束:
相关问题 更多 >
编程相关推荐