Skip to content

Instantly share code, notes, and snippets.

@rer145
Created November 7, 2017 00:11
Show Gist options
  • Save rer145/ecbe855d19cf31a81277e19ee3b81e08 to your computer and use it in GitHub Desktop.
Save rer145/ecbe855d19cf31a81277e19ee3b81e08 to your computer and use it in GitHub Desktop.
Input and output file prompts in python
import os.path
def input_file_prompt():
""" () -> string
Precondition: none
This function returns back a filename that the user wants to read data from. It also checks to see
if the file already exists and if not, informs the users and prompts them to try again.
"""
fileName = input('Enter the name of the file to read from: ')
while not os.path.isfile(fileName):
print('The specified file can not be found. Please try again.')
fileName = input('Enter the name of the file to read from: ')
return fileName
def output_file_prompt():
""" () -> string
Precondition: none
This function returns back a filename that the user wants to write data to. It also checks to see
if the file already exists and confirms with the user if they want to overwrite it. The function
returns back an empty string if the user has canceled out of the operation.
"""
fileName = input('Enter the name of the file to write to: ')
while os.path.isfile(fileName):
overwrite = input('The file exists. Do you want to choose another file name ("choose"), overwrite the file ("overwite"), or cancel ("cancel")? ')
overwrite = overwrite.strip().lower()
if overwrite == 'choose':
#prompt again
#do name check again
return output_file_prompt()
elif overwrite == 'overwrite':
#user wants to use same file name so return that
return fileName
elif overwrite == 'cancel':
return ''
else:
continue
return fileName
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment