使用argparse创建输出文件

7

我一直在编写程序中使用argparse,但它似乎不能创建指定的输出文件。

我的代码如下:

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)

我也尝试过:

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)

发生的错误是:
    output_file.write("%s\n" % item)
NameError: name 'output_file' is not defined

请问有人可以解释一下为什么我遇到这个错误以及我如何解决它吗?

我的所有代码:

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)

with open(output, 'w') as output_file 后面有没有加上 : 呢?除了缺少冒号和略微夸张的缩进之外,看起来还不错。 - Jon Clements
我刚刚在末尾加了一个冒号并出现了以下错误: with open(output, 'w') as output_file: NameError: name 'output' is not defined - Tom
3个回答

7
您漏掉了实际解析参数的部分:
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() 将给你一个对象,你可以通过长选项名称(去掉破折号)访问该对象并获取参数。


那一部分是代码的一部分,但我忘记将其添加到我发布的内容中,已编辑以包括我的所有代码。 - Tom
@chepner,是的,你说得对,我应该添加类似于output = str(args.output)这样的内容,但现在问题变成了output_file.write("%s\n" % item) NameError: name 'item' is not defined,这与Jacobo de Vera所说的大致相同,但是如何像你说的那样定义一个item呢?由于我是编程新手,所以不确定。 - Tom
对 @Jacobo de Vera,我再次放入你的代码以查看发生了什么,并出现了这个错误:output_file.write("%s\n" % item) ^ IndentationError: 期望缩进块,在file下面的e处。如果将if语句与open_files放在一起可以解决此问题,但是会出现以下错误:if line3: output_file.write("%s\n" % item) NameError: name 'item'未定义。 - Tom
那么,“item”是什么?看起来,“item”是您的程序逻辑需要定义的东西:输出文件的内容应该是什么? - chepner
我刚刚尝试使用以下代码行,但程序在创建文件后停止了,因此它只是一个空文件:output = str(args.output) output_file= open(output, "w") - Tom
显示剩余4条评论

3

我认为你的答案几乎是最正确的。唯一的问题是output_file没有从参数中读取:

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)

1
当我运行你的脚本时,我得到以下结果:
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

你的脚本中没有任何地方执行output = ...

我们可以通过以下方式进行更正:

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

argparse 将返回值作为 args 对象的属性。

现在我得到:

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

再次强调,没有item = ...这一行。

item应该是什么?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接