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?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062
  • Do you want the file name to come from user input or a command line argument? (e.g. python myScript.py inputfile.txt) – Rob Lourens Jul 27 '10 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. – chimeracoder Jul 27 '10 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. – John Smith Jun 09 '13 at 19:48

5 Answers5

206

Use the raw_input() function to get input from users (2.x):

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

or just:

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

or if in Python 3.x:

filename = input('Enter a file name: ')
Josh
  • 49
  • 5
David Webb
  • 190,537
  • 57
  • 313
  • 299
119

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

Sunny Tambi
  • 2,393
  • 3
  • 23
  • 27
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]

Nikolaus Gradwohl
  • 19,708
  • 3
  • 45
  • 61
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)
Kyle Falconer
  • 8,302
  • 6
  • 48
  • 68
  • ... Doesn't really answer the question... – wizzwizz4 Jun 08 '16 at 13:52
  • @wizzwizz4 it absolutely does. Did you read what I put? – Kyle Falconer Jun 08 '16 at 13:53
  • 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. – wizzwizz4 Jun 08 '16 at 13:59
  • `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. – Kyle Falconer Jun 08 '16 at 14:01
  • Makes more sense now. – wizzwizz4 Jun 08 '16 at 14:04
  • I had some strange behavior while using in this in my solution. Specific error I was getting was `UnboundLocalError: local variable 'input' referenced before assignment`. To fix it I reassigned input via the `builtins` module. `try: input = raw_input except NameError: import builtins; input = builtins.input; pass`. I've added semi-colons just for readability in this comment. – nmante Jun 25 '16 at 09:48
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)
Ezra A.Mosomi
  • 511
  • 5
  • 4