获取用户input

我正在运行这个:

import csv import sys reader = csv.reader(open(sys.argv[0], "rb")) for row in reader: print row 

我得到这个回应:

 ['import csv'] ['import sys'] ['reader = csv.reader(open(sys.argv[0]', ' "rb"))'] ['for row in reader:'] [' print row'] >>> 

对于sys.argv[0]我希望它提示我input一个文件名。

我如何得到它来提示我input文件名?

在python 3.x中,使用input()而不是raw_input()

使用raw_input()函数从用户(2.x)获取input:

 print "Enter a file name:", filename = raw_input() 

要不就:

 filename = raw_input('Enter a file name: ') 

或者如果在Python 3.x中:

 filename = input('Enter a file name: ') 

sys.argv[0]不是第一个参数,而是当前正在执行的python程序的文件名。 我想你想要sys.argv[1]

为了补充上面的答案到一些更可重用的东西,我想出了这个,它继续提示用户,如果input被认为是无效的。

 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 

它可以像这样使用,具有validationfunction:

 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) 

使用以下简单的方法通过提示以交互方式获取用户数据作为所需的参数。

版本: Python 3.X

 name = input('Enter Your Name: ') print('Hello ', name)