python copy selected lines from one file to another using argparse or getopt

John Gordon gordon at panix.com
Wed Jan 8 17:53:24 EST 2014


In <bc99af4e-8031-477c-877f-a5460f8a09ab at googlegroups.com> sagarnildass at gmail.com writes:

> But I don't know how to:

> Include multiple search word and exclude words
> How to denote them by -e and -s. I have seen the argparse and the getopt
> tutorial. But there's no tutorial on this specific topic.

This should help you get started:

    import argparse

    parser = argparse.ArgumentParser()

    parser.add_argument('-search', '-s', help='a word to search',
        action='append', required=True)
    parser.add_argument('-exclude', '-e', help='a word to exclude from search',
        action='append')
    parser.add_argument('input_file')
    parser.add_argument('output_file')

    args = parser.parse_args()

Assuming the user provided correct arguments, the args object will have
these attributes:

    args.search - a list of words to search for.
    args.exclude - a list of words to exclude.  Can be None.
    args.input_file - the input file name.
    args.output_file - the output file name.

-- 
John Gordon         Imagine what it must be like for a real medical doctor to
gordon at panix.com    watch 'House', or a real serial killer to watch 'Dexter'.




More information about the Python-list mailing list