144

I am running this:

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

And I get this in response:

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

For the sys.argv[0] I would like it to prompt me to enter a filename.

How do I get it to prompt me to enter a filename?

3
  • Do you want the file name to come from user input or a command line argument? (e.g. python myScript.py inputfile.txt) Commented Jul 27, 2010 at 15:28
  • 2
    Since you're just beginning in Python, it might be a good idea to look through a tutorial and learn the basics of the language, rather than try to learn just the features you need and search for the answers on StackOverflow when you can't find something. It'll take more time, sure, but you'll get a much better understanding of the language. Commented Jul 27, 2010 at 15:39
  • 8
    @chimeracoder: granted he went the easy way, but it's exactly these questions that allow me to find an answer fast if I'm just 'looking it up' on google. Also for a small project and not so much time python is the tool of choice because of it's simplicity, it's good not to have to read up a whole tutorial. Commented Jun 9, 2013 at 19:48

5 Answers 5

206

Use the input() function to get input from users:

print("Enter a file name:")
filename = input()

or just:

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

In Python 2, the equivalent was raw_input().

Sign up to request clarification or add additional context in comments.

3 Comments

In Python 3, it's just input() - caution : there is an input method in 2.x too, but it eval()s the input and is therefore evil.
Any way to write a prompt that can work for both?
@Agostino try: input = raw_input ; except NameError: pass; And then use input freely. (Basically, if raw_input exists, assign it to the name input. If not, well, you're in python3). Semicolons are actually supposed to be newlines
119

In python 3.x, use input() instead of raw_input()

3 Comments

Is there a specific reason why input() is better than raw_input() since 3.x? Other than it being easier to type...
@SilverRingvee raw_input doesn't exist.
a pretty good reason.
28

sys.argv[0] is not the first argument but the filename of the python program you are currently executing. I think you want sys.argv[1]

1 Comment

Not what he asked for, but useful none the less
8

To supplement the above answers into something a little more re-usable, I've come up with this, which continues to prompt the user if the input is considered invalid.

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

It can be used like this, with validation functions:

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)

6 Comments

... Doesn't really answer the question...
@wizzwizz4 it absolutely does. Did you read what I put?
It pollutes the global namespace (overwriting input in Python 2), and it looks really hard to use (what is self?). I've upvoted, but it needs some work on the documentation.
self wasn't supposed to be there so I removed it. I changed input for Python 2/3 compatibility. Check out the comments in the other answers.
Makes more sense now.
|
8

Use the following simple way to interactively get user data by a prompt as Arguments on what you want.

Version : Python 3.X

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.