how do we keep prompting the user to enter the right file name when the file name is wrong? import csv if __name__ == '__main__': try: a = input('Enter name of file:\n') total1 = 0 total2 = 0 result = 0 i = 0 sums = 0 with open(a, 'r+' ) as file : line = file.readline() while line != '' : value = line.rstrip('\n').split(',') total1 = total1 + int(value[0]) total2 = total2 + int(value[1]) i = i +1 line = file.readline() print('File to be processed is: ', '{}'.format(a)) print('Average weight =', '{:.2f}'.format((total1/i), )) print('Average height = ', '{:.2f}'.format((total2/i), )) except IOError: print('File', a, 'not found.')
how do we keep prompting the user to enter the right file name when the file name is wrong?
import csv
if __name__ == '__main__':
try:
a = input('Enter name of file:\n')
total1 = 0
total2 = 0
result = 0
i = 0
sums = 0
with open(a, 'r+' ) as file :
line = file.readline()
while line != '' :
value = line.rstrip('\n').split(',')
total1 = total1 + int(value[0])
total2 = total2 + int(value[1])
i = i +1
line = file.readline()
print('File to be processed is: ', '{}'.format(a))
print('Average weight =', '{:.2f}'.format((total1/i), ))
print('Average height = ', '{:.2f}'.format((total2/i), ))
except IOError:
print('File', a, 'not found.')
The given code keep prompting the user to enter the right file name until the file name is not correct:
import csv
import os
def main():
a = input('Enter name of file:\n') # read the file name
while True:
if(os.path.exists(a)): # check for file existence
total1 = 0
total2 = 0
result = 0
i = 0
sums = 0
with open(a, 'r+' ) as file :
line = file.readline()
while line != '' :
value = line.rstrip('\n').split(',')
total1 = total1 + int(value[0])
total2 = total2 + int(value[1])
i = i +1
line = file.readline()
print('File to be processed is: ', '{}'.format(a))
print('Average weight =', '{:.2f}'.format((total1/i), ))
print('Average height = ', '{:.2f}'.format((total2/i), ))
return
else: # if file is not exists prompt again to read name of file
print("The file you selected does not exist, please try again")
a = input("Enter name of file again: ")
if __name__ == '__main__':
main()
Step by step
Solved in 2 steps with 2 images