l--*_*''' 137 python user-input
我正在运行这个:
import csv
import sys
reader = csv.reader(open(sys.argv[0], "rb"))
for row in reader:
print row
Run Code Online (Sandbox Code Playgroud)
我得到了回应:
['import csv']
['import sys']
['reader = csv.reader(open(sys.argv[0]', ' "rb"))']
['for row in reader:']
[' print row']
>>>
Run Code Online (Sandbox Code Playgroud)
因为sys.argv[0]我希望它提示我输入文件名.
如何让它提示我输入文件名?
Dav*_*ebb 202
使用该raw_input()函数从用户(2.x)获取输入:
print "Enter a file name:",
filename = raw_input()
Run Code Online (Sandbox Code Playgroud)
要不就:
filename = raw_input('Enter a file name: ')
Run Code Online (Sandbox Code Playgroud)
或者如果在Python 3.x中:
filename = input('Enter a file name: ')
Run Code Online (Sandbox Code Playgroud)
Sun*_*mbi 114
在python 3.x中,使用input()而不是raw_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
Run Code Online (Sandbox Code Playgroud)
它可以像这样使用,具有验证功能:
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)
Run Code Online (Sandbox Code Playgroud)
小智 7
使用以下简单方法通过提示交互式获取用户数据作为您想要的参数.
版本:Python 3.X
name = input('Enter Your Name: ')
print('Hello ', name)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
404918 次 |
| 最近记录: |