8

I'm developing a Python script that will utilize CLI arguments to convert a .xls/.xlsx file into a .csv. Because .xsl/.xlsx files can have multiple sheets, each sheet needs to be individually converted into separate .csv files. What I would like to do is use argparse to add a required parameter to specify which sheet to convert and an optional parameter to specify what the resulting .csv should be named. Here is an example of how I would like the command to look:

python converter.py --sheets <sheet-name> [sheet-rename]

So I'm not sure how to add an argument with two parameters like this using argparse.

Additionally, I would like to add more functionality to this argument. If it's possible, I'd like to make it possible to repeat arguments to allow for more sheets to be converted. I'm not sure how the command syntax would look but something like this:

python converter.py --sheets (<sheet-name> [sheet-rename])...
python converter.py --sheets sheet1 sheet1_rename sheet2 sheet2_rename

This may end up being too complicated but any input would be great.

1 Answer 1

12

--sheet can be defined as an option that takes two arguments, both of which are accumulated in a list.

p.add_argument('--sheet', action='append', nargs=2)

Calling python converter.py --sheet old1 new1 --sheet old2 new2 would produce a list of lists:

>>> print p.parse_args("--sheet old1 new1 --sheet old2 new2".split())
Namespace(sheet=[['old1', 'new1'], ['old2', 'new2']])
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! I didn't realize that you could call an optional argument more than once to make a list using action='append'. One thing I am changing is setting nargs='+' since I want providing the rename to be an option, if it isn't specified then the .csv will be saved with the same name as the sheet. Thanks!

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.