I would like to specify a file for manipulation from the command line. I am new to python so I'm not really sure how to begin this. I am guessing that I need some options?

You need what are called 'command line arguments'. Dive into python has a great section explaining command line arguments. But in essence you could do something like this:

import sys
if sys.argv:
    print "The first command line argument i recieved was:",sys.argv[0]

Then we would run our code like this:

python filename.py ThisIsTheArgument

And the result would print the following out

The first command line argument i recieved was: ThisIsTheArgument

So i'm sure you can see that instead of writing 'ThisIsTheArgument' that you could put a path to a file there instead and then do things to it in your program. Anyway, have a look at the link above, it'll help you out :)

Edited 6 Years Ago by Paul Thompson: n/a

Good answer but permit me to suggest a minor change to the above example.

#!/usr/bin/env python
#argecho.py
import sys
if sys.argv:
    print "The name of this program is:",sys.argv[0]
    print "The first command line argument I received is:",sys.argv[1]
    print "The second command line argument I received is:",sys.argv[2]
Comments
Woops :) my bad. Nicely done

Ok, but I need to do this for an arbitrary number of file names. Is there any way to completely remove the first element in the array and make the file path the first element?

Ok, but I need to do this for an arbitrary number of file names. Is there any way to completely remove the first element in the array and make the file path the first element?

Create an empty list and append what you want from sys.argv into your list.

import sys

# there is a commandline
if len(sys.argv) > 1:
    arglist = []
    # sys.argv[0] is the program filename, slice it off
    for arg in sys.argv[1:]: #Slice of sys.argv starting at sys.argv[1] up to and including the end
        arglist.append(arg)
else:
    print "usage %s arg1 arg2 [arg3 ...]" % sys.argv[0]
    sys.exit(1)

# if the arguments were This.txt That.txt Other.log
# arglist should be ['This.txt', 'That.txt', 'Other.log']
print(arglist)
Comments
nice
This question has already been answered. Start a new discussion instead.