0

I some lines of code that read a csv file in a certain format. What I'd like now (and couldn't figure out a solution for) is that the file name stops being stale and becomes an actual user input when calling the python program. Now I have a static file name in the code, eg:

reader = csv.reader(open("file.csv", "rb"))

I'd like this to become an information provided by the user. Is this done using raw_input or is there a way to do it by having the user writing something in the lines of:

python testfile.py --input:file.csv

Appreciate your help in advance!

5 Answers 5

5

The simplest way is to write your script like this:

import sys
reader = csv.reader(open(sys.argv[1], "rb"))

and then run it like this:

python testfile.py file.csv

You should put in some error checking, eg:

if len(sys.argv) < 2:
    print "Usage..."
    sys.exit(1)

For more power, use the bult in optparse / argparse library.

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

Comments

2

For reference the optparse (http://docs.python.org/library/optparse.html) version would look something like this.

import optparse

parser = optparse.OptionParser()
parser.add_option("-i","--input",dest="filename")
(options,args) = parser.parse_args()

thefile = options.filename
reader = csv.reader(thefile,"rb")

Which would let you call either

python script.py -i foo.dat
python script.py --input foo.dat

1 Comment

Whats the way for user defined output csv?
1

You can use optparse (argparse after 2.7) or getopt to parse command line parameters. Only use getopt if you're already familiar with argument parsing in C. Otherwise argparse is the easiest to use.

Comments

0

Maybe the argparse python module fits your depends:

http://docs.python.org/library/argparse.html

The old optparse is deprecated.

Comments

0

You can access sys.argv which is an array of the inputs. But keep in mind that the first argument is the actual program itself.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.