我正在运行:
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]
我希望它提示我输入文件名。
如何让它提示我输入文件名?
答案 0 :(得分:202)
使用raw_input()
function从用户(2.x)获取输入:
print "Enter a file name:",
filename = raw_input()
或只是:
filename = raw_input('Enter a file name: ')
或者如果在Python 3.x中:
filename = input('Enter a file name: ')
答案 1 :(得分:111)
在python 3.x中,使用file
代替input()
答案 2 :(得分:27)
sys.argv[0]
不是第一个参数,而是您当前正在执行的python程序的文件名。我想你想要sys.argv[1]
答案 3 :(得分:8)
为了将上述答案补充到一些可重复使用的内容中,我已经提出了这个问题,如果输入被视为无效,则会继续提示用户。
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
可以像这样使用验证函数:
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)
答案 4 :(得分:7)
以交互方式使用以下简单方法 通过提示获取用户数据作为您想要的参数。
版本: Python 3.X
name = input('Enter Your Name: ')
print('Hello ', name)