开发者

User defined input csv file

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 开发者_C百科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!


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.


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


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.


Maybe the argparse python module fits your depends:

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

The old optparse is deprecated.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜