Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using argparse to create output file

I have been using argparse in a program I am writing however it doesnt seem to create the stated output file.

My code is:

parser.add_argument("-o", "--output", action='store', dest='output', help="Directs the output to a name of your choice")
with open(output, 'w') as output_file:
            output_file.write("%s\n" % item)

I have also tried:

parser.add_argument("-o", "--output", action='store', type=argparse.FileType('w'), dest='output', help="Directs the output to a name of your choice")
    output_file.write("%s\n" % item)

The error that occurs is :

    output_file.write("%s\n" % item)
NameError: name 'output_file' is not defined

Can someone please explain why I am having this error occuring and how I could solve it?

All my code:

from __future__ import print_function
from collections import defaultdict
from itertools import groupby
import argparse #imports the argparse module so it can be used
from itertools import izip
#print = print_function




parser = argparse.ArgumentParser() #simplifys the wording of using argparse as stated in the python tutorial
parser.add_argument("-r1", type=str, action='store',  dest='input1', help="input the forward read file") # allows input of the forward read
parser.add_argument("-r2", type=str, action='store', dest='input2', help="input the reverse read file") # allows input of the reverse read
parser.add_argument("-v", "--verbose", action="store_true", help=" Increases the output, only needs to be used to provide feedback to Tom for debugging")
parser.add_argument("-n", action="count", default=0, help="Allows for up to 5 mismatches, however this will reduce accuracy of matching and cause mismatches. Default is 0")
#parser.add_argument("-o", "--output", action='store', type=argparse.FileType('w'), dest='output', help="Directs the output to a name of your choice")
parser.add_argument("-fastq", action="store_true", help=" States your input as fastq format")
parser.add_argument("-fasta", action="store_true", help=" States your input as fasta format")
parser.add_argument("-o", "--output", action='store', dest='output', help="Directs the output to a name of your choice")


args = parser.parse_args()
def class_chars(chrs):
    if 'N' in chrs:
        return 'unknown'
    elif chrs[0] == chrs[1]:
        return 'match'
    else:
        return 'not_match'

with open(output, 'w') as output_file:



    s1 = 'aaaaaaaaaaN123bbbbbbbbbbQccc'
    s2 = 'aaaaaaaaaaN456bbbbbbbbbbPccc'
    n = 0
    consec_matches = []
    chars = defaultdict(int)

    for k, group in groupby(zip(s1, s2), class_chars):
        elems = len(list(group))
        chars[k] += elems
        if k == 'match':
            consec_matches.append((n, n+elems-1))
        n += elems

    print (chars)
    print (consec_matches)
    print ([x for x in consec_matches if x[1]-x[0] >= 9])
    list = [x for x in consec_matches if x[1]-x[0] >= 9]
    flatten_list= [x for y in list for x in y]
    print (flatten_list)
    matching=[y[1] for y in list for x in y if x ==0 ]
    print (matching)
    magic = lambda matching: int(''.join(str(i) for i in matching)) # Generator exp.
    print (magic(matching))
    s2_l = s2[magic(matching):]
    line3=s1+s2_l
    print (line3)
    if line3:
        output_file.write("%s\n" % item)
like image 892
Tom Avatar asked May 09 '14 14:05

Tom


People also ask

What does Argparse return?

Later, calling parse_args() will return an object with two attributes, integers and accumulate . The integers attribute will be a list of one or more ints, and the accumulate attribute will be either the sum() function, if --sum was specified at the command line, or the max() function if it was not.

What is Store_true in Python?

The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present. The source for this behavior is succinct and clear: http://hg.python.org/cpython/file/2.7/Lib/argparse.py#l861.


1 Answers

You are missing the bit where the arguments are actually parsed:

parser.add_argument("-o", "--output", help="Directs the output to a name of your choice")
args = parser.parse_args()
with open(args.output, 'w') as output_file:
    output_file.write("%s\n" % item)

parser.parse_args() will give you an object from which you can access the arguments by name using the long option name bar the dashes.

like image 108
Jacobo de Vera Avatar answered Sep 28 '22 07:09

Jacobo de Vera