I am trying to write a program that asks for a specific file name and then processes the input file name to make a list out of it. The limitation is that the user has only three chances to type the correct file name. Here are my codes:
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()
ERROR:
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
I would appreciate any suggestion. Thanks
open_file()? just callfile_name_tries(). I'm a little confused. Do you want to interactively checks whether file exist? or ask user to enter 3 files and check which files exist? You need to clarify the task for us to help you better. =)