-1

I am trying to process a file passed as a command line argument. Right now there is only one argument, but I plan to add others.

Here is my code so far:

import argparse

parser = argparse.ArgumentParser(description="Sample arg parsing")

parser.add_argument('-f',type=file)

try:
    print parser.parse_args()
except IOError, msg:
    parser.error(str(msg))

I can't figure out how to pass the argument to file handle to open and process. And yes, I am a n00b. The try block is just there for testing.

CraigBoyd
  • 9
  • 2
  • arguments are text - it can't be file - but you can use [FileType objects](https://docs.python.org/3/library/argparse.html#filetype-objects) to convert filename to file. – furas Jan 29 '16 at 04:08
  • Thanks for that link. The seems to say that by using FileType it is opening the file implicitly for me. So I am still stuck with how do I reference it so that I can process it? – CraigBoyd Jan 29 '16 at 04:29
  • `args = parser.parse_args()` and then `args.f` because you used name `-f` – furas Jan 29 '16 at 04:41
  • Possible duplicate of [Command Line Arguments In Python](http://stackoverflow.com/questions/1009860/command-line-arguments-in-python) –  Jan 29 '16 at 05:17

1 Answers1

0

You need to pass the filename as a string. Then, you can use open() to open the file from the filename. Refer to the python docs here (7.2 - Reading & Writing Files).

intcreator
  • 4,206
  • 4
  • 21
  • 39
Patrick Finnigan
  • 1,767
  • 16
  • 28
  • OK...that makes sense. But how do I reference the passed argument to set it equal to a string? – CraigBoyd Jan 29 '16 at 04:26
  • It will already be a string, you just have to read its value. The first example here shows you how to read an argument value: https://docs.python.org/2/howto/argparse.html#introducing-positional-arguments – Patrick Finnigan Jan 29 '16 at 04:33
  • Ah! So whatever is in the first position of the add_argument method becomes the argument's name that can then be referenced, right? – CraigBoyd Jan 29 '16 at 04:42
  • Thanks Patrick and furas ~ between the two of you I got there! – CraigBoyd Jan 29 '16 at 04:48