BYU logo Computer Science

Handling arguments

When we run a Python program from the command line, we can give it arguments:

python this_file.txt new_file.txt

This will call the program in with two arguments — this_file.txt and new_file.txt. This program could then read in all the lines of this_file.txt and copy those same lines into new_file.txt.


To get the arguments into your program, Python puts them into a list called argv. To use argv, you have to:

import sys

Then you can get the arguments in sys.argv:

import sys

print('The contents of sys.argv are:')

If you put this in a file called, and then run this program as above:

python this_file.txt new_file.txt

then this will print:

The contents of sys.argv are:
['', 'this_file.txt', 'new_file.txt']

Notice how the first argument in the list is the name of the program. Then the second and third (and any other) arguments come after that.

Accessing individual arguments

Let’s talk about how the Python script gets access to these arguments. In your Python script, you can do the following:

import sys

input_file = sys.argv[1]
output_file = sys.argv[2]

Now if we run:

python this_file.txt new_file.txt

then, input_file will be equal to this_file.txt and output_file will be equal to new_file.txt.

Copying a file

Let’s see how this would work in an entire program. Here is a program that will copy a file:

import sys

def read_lines(filename):
    """ read all the lines in a file (it is already open) and return them
    as a list """
    with open(filename) as file:
        return list(file)

def write_lines(filename, lines):
    """ write a list of lines to the given filename (it is no open) """
    with open(filename, 'w') as file:
        for line in lines:

def main(input_file, output_file):
    """ copy the input file to the output file"""
    lines = read_lines(input_file)
    write_lines(output_file, lines)

# Call the main function with arguments 1 and 2 -- which should be the input file
# and the output file
main(sys.argv[1], sys.argv[2])

You can see that we get the two arguments and, instead of storing them in variables, immediately give them to the main() function. Now main() can call the read_lines() function to read all the lines from the input_file, and then write_lines() to write the list of lines into the output_file.