写入a不会产生新文件,但不会产生错误

2024-05-16 14:27:24 发布

您现在位置:Python中文网/ 问答频道 /正文

目标是:

  1. 在argparse中取一个参数
  2. 检验这个论点是否成立
  3. 如果为true,则使用该参数后指定的名称编写一个文件

例如: 在命令行中:

$ python printfile.py --out_arg fileOutput.txt

。。。会产生文件输出.txt在与相同的目录中打印文件.py你知道吗

代码:

def parse_arguments():
    options = parse_arguments()
    #output arguments
    parser.add_argument("--out_arg", action='store', default=False, dest='out_arg',  
     help="""Output file """)

def print_output(seqID, seq, comm):
    # "a" append is used since this is the output of a for loop generator
    if options.out_arg
        outputfh = open(options.out_33,"a")
        outputfh.write("@{}\n{}\n{}\n+".format(seqID, seq, comm))
    else:
        sys.stderr.write("ERR: sys.stdin is without sequence data")

然而,当我调用print_output from def main()-未显示-传入感兴趣的元组(seqID,seq,comm)时,不会写入任何文件,也不会给出任何错误消息。是argparse参数没有将输入的文件存储为dest吗?在尝试写入时是否使用了文件句柄?你知道吗


Tags: 文件pytxtoutput参数isdefarg
1条回答
网友
1楼 · 发布于 2024-05-16 14:27:24

您从未对输出文件调用close。Python的编写在某种程度上得到了缓冲,根据doc,如果不调用flushclose,就不能保证所有的输出都在文件中(或一个文件)。你知道吗

您应该始终使用with open() as ofile:语法执行文件IO,以确保文件正确刷新/关闭:

if options.out_arg:
    with open(options.out_33, 'a') as outputfh:
        outputfh.write(...)
else:
    ...

当然,所有这些都假设您实际上在某个地方调用print_output,而您的代码没有显示。而且options.out_33是一个相对路径,而不是一个绝对路径,否则文件将不会在您期望的地方结束。你知道吗

相关问题 更多 >