Para complementar las respuestas anteriores en algo un poco más reutilizable, yo he llegado con esto, que continúa solicitando el usuario si la entrada se considera inválida.
try:
input = raw_input
except NameError:
pass
def prompt(message, errormessage, isvalid):
"""Prompt for input given a message and return that value after verifying the input.
Keyword arguments:
message -- the message to display when asking the user for the value
errormessage -- the message to display when the value fails validation
isvalid -- a function that returns True if the value given by the user is valid
"""
res = None
while res is None:
res = input(str(message)+': ')
if not isvalid(res):
print str(errormessage)
res = None
return res
Puede ser utilizado como éste, con funciones de validación:
import re
import os.path
api_key = prompt(
message = "Enter the API key to use for uploading",
errormessage= "A valid API key must be provided. This key can be found in your user profile",
isvalid = lambda v : re.search(r"(([^-])+-){4}[^-]+", v))
filename = prompt(
message = "Enter the path of the file to upload",
errormessage= "The file path you provided does not exist",
isvalid = lambda v : os.path.isfile(v))
dataset_name = prompt(
message = "Enter the name of the dataset you want to create",
errormessage= "The dataset must be named",
isvalid = lambda v : len(v) > 0)
¿Quieres que el nombre del archivo que venir de entrada de usuario o un argumento de línea de comandos? (por ejemplo, python myScript.py inputfile.txt) –
Como recién está comenzando en Python, podría ser una buena idea consultar un tutorial y aprender los conceptos básicos del idioma, en lugar de tratar de aprender solo las características que necesita y busca las respuestas en StackOverflow cuando no puedes encontrar algo. Tomará más tiempo, claro, pero comprenderá mucho mejor el idioma. – chimeracoder
@chimeracoder: admitió que fue por el camino fácil, pero son exactamente estas preguntas las que me permiten encontrar una respuesta rápida si solo estoy 'buscando' en google. También para un proyecto pequeño y no tanto tiempo Python es la herramienta de elección debido a su simplicidad, es bueno no tener que leer todo un tutorial. –