7

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)
Tom
  • 469
  • 4
  • 7
  • 16
  • Do you have a `:` after `with open(output, 'w') as output_file`? Otherwise apart from the missing colon and somewhat exaggerated indentation - it looks fine – Jon Clements May 09 '14 at 14:26
  • I have just edited it with a : at the end and this error occurs: with open(output, 'w') as output_file: NameError: name 'output' is not defined – Tom May 09 '14 at 14:28

3 Answers3

7

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.

Jacobo de Vera
  • 1,863
  • 1
  • 16
  • 20
  • That bit it part of the code but I forgot to add it to what I put up, have edited to include all my code. – Tom May 09 '14 at 14:31
  • @Tom Your code tries to use `output` as the file name, but you need to use the `output` attribute of the return value from `parse_args` instead. – chepner May 09 '14 at 14:36
  • Try running my example, just define `item` before. Note how it calls `args.output`. – Jacobo de Vera May 09 '14 at 14:38
  • @chepner yeah you were correct that I should have added the something like output = str(args.output) but the issue now changes to output_file.write("%s\n" % item) NameError: name 'item' is not defined which along the lines of what Jacobo de Vera was saying but how do I define and item before as you say? New to coding so unsure. – Tom May 09 '14 at 14:46
  • Right @ Jacobo de Vera I have again put in your code to see whats going on and this error is occuring: output_file.write("%s\n" % item) ^ IndentationError: expected an indented block with the ^ under the e in file. Just incase this could be solved by putting the if statement the the open_files together I have and this error occurs: if line3: output_file.write("%s\n" % item) NameError: name 'item' is not defined – Tom May 09 '14 at 14:50
  • Well, what is `item`? It appears that `item` is something that your program logic needs to define: what are the contents of the output file supposed to be? – chepner May 09 '14 at 14:50
  • The output file will be contain the line aaaaaaaaaaN123bbbbbbbbbbQcccaN456bbbbbbbbbbPccc from the above example as the 2 sequences will be matched and merged together. I am unsure what item is as I found the write line on another thread here. – Tom May 09 '14 at 14:55
  • I have just tried using the following line but the program stopped after creating the file so its just an empty file: output = str(args.output) output_file= open(output, "w") – Tom May 09 '14 at 15:03
  • The output = str(args.output) output_file= open(output, "w") solution solved the issue when place after the def class_chars line and the new file was made and written to. Thanks for all your help. – Tom May 09 '14 at 15:08
3

I think you almost had the most correct answer. The only problem is output_file was not read from the args:

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 is not defined, you want to read args.output to get the output_file
output_file = args.output
#now you can write to it
output_file.write("%s\n" % item)
Charles L.
  • 5,795
  • 10
  • 40
  • 60
1

When I run your script I get:

Traceback (most recent call last):
  File "stack23566970.py", line 31, in <module>
    with open(output, 'w') as output_file:
NameError: name 'output' is not defined

There's no place in your script that does output = ....

We can correct that with:

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

argparse returns values as attributes of the args object.

Now I get:

Traceback (most recent call last):
  File "stack23566970.py", line 62, in <module>
    output_file.write("%s\n" % item)
NameError: name 'item' is not defined

Again, there's no item = ... line.

What is item supposed to be?

hpaulj
  • 221,503
  • 14
  • 230
  • 353