user3234810
user3234810

Reputation: 482

User defined input in python

I have a script that reads .csv files and I want to set it up so it can be run as follows

python script.py file1.csv file2.csv file3.csv

I would also like the output of the script (which is a .csv) to name the csv's based on the input.

Here are the current lines

with open("test2.csv","wb") as f:
    output = csv.writer(f) 
    for line in csv.reader(open("test.csv")):

I have tried using raw_input but it doesnt seem to be appropriate for the job, is there another way?

Upvotes: 0

Views: 103

Answers (2)

d18s
d18s

Reputation: 53

Adding the following to your script:

import sys
print sys.argv

And running:

python script.py file1.csv file2.csv file3.csv

You will get the following output:

['script.py', 'file1.csv', 'file2.csv', 'file3.csv']

I.e., sys.argv contains a list, whose first item is the name of the script being run, and whose subsequent items are the options / filenames being passed.

Upvotes: 2

Jonas Schäfer
Jonas Schäfer

Reputation: 20738

You can either use sys.argv, or for more easy and sophisticated parsing the argparse standard library.

An example would be:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("infile")
parser.add_argument("outfile")
args = parser.parse_args()

with open(args.outfile, "wb") as f:
    output = cvs.writer(f)
    for line in csv.reader(open(args.infile)):

For more sophisticated examples, such as accepting a variable amount of input files and exactly one output file, please see the argparse documentation linked above or the argparse tutorial.

Upvotes: 5

Related Questions