How can I perform an action if a users input is the name of a file in a directory. Python -
i trying make program user can create sets of data, having difficult time figuring out how handle user picking user picking name out of list of files edit or view. here how display files can choose from. how can allow them choose 1 of available files without hardcoding each individual one?
available_files = os.listdir('./dsc_saves/') print(available_files) user_input = input('file name: ') what avoid doing following:
if user_input == available_files[0]: #do action elif user_input == available_files[1]: #do action 2 elif user_input == available_files[2]: #do action 3
as mentioned, can using in on list of available files follows:
available_files = os.listdir('./dsc_saves/') print(available_files) while true: user_input = input('file name: ') if user_input in available_files: break print("you have selected '{}'".format(user_input)) alternatively, make easier type, present user numeric menu choose follows:
available_files = os.listdir('./dsc_saves/') index, file_name in enumerate(available_files, start=1): print('{:2} {}'.format(index, file_name)) while true: try: user_input = int(input('please select file number: ')) if 1 <= user_input <= len(available_files): selected_file = available_files[user_input-1] break except valueerror e: pass print("you have selected '{}'".format(selected_file)) both solutions continue prompting until valid file name has been entered.
so example see following output:
1 test1.txt 2 test2.txt please select file number: 3 please select file number: 2 have selected 'test2.txt'
Comments
Post a Comment