r/pythonhelp • • Jan 30 '23

Loop feature to ask the user to enter the file name until they press "n".

Hello I need help with a python project. I have been asked to create a feature that would allow the user to enter a file name and prompt an error message if the file cannot be opened. The process should continue to as ask for a valid file name until the file can be opened or the user types "n". Yet I am not sure where to implement the loop.

So far I came up with this:

def open_file(self):
try:
fname = input("Enter a filename for network data: ")
with open(fname, 'r') as f:
num_members = int(f.readline().strip())
for line in f:
member, friend = line.strip().split()
if member in network:
network[member].append(friend)
else:
network[member] = [friend]

except IOError:
print("File does not exist.")
return False
return True

Yet I am not sure where to implement the loop so that when the file does not exist the user must be prompted to enter the file again until they press "n".

Any help would be much appreciated. :)

2 Upvotes

1 comment sorted by

1

u/slowlycatchiemonkey Jan 30 '23

You need to look at a python while loop

This is a loop that will continue indefinitely until some condition is met.

So you set a value on some variable before the loop, and then check that value each time you iterate through the loop.

Your code is halfway there.

Happy to help if you need it. You've actually posted some code, so kudos. GMT though