0

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?

2
  • So what are your questions acutally? You need help with setting up your Python script to accept 3 CSVs as arguments and setting you output file's filename to some user input? Commented Feb 5, 2014 at 10:26
  • Just new to programming/python and wanted to know if there was a better way to do things than raw_input Commented Feb 5, 2014 at 10:30

2 Answers 2

5

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.

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

1 Comment

Something like ap.add_argument('files', metavar='CSV', type=str, nargs='+', help='data file') could be useful in OP's case, to make it completle effortless for him =)
2

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.

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.