【问题标题】:Writing out to a gives no new file, but no error either写出 a 没有新文件,但也没有错误
【发布时间】:2014-12-13 09:31:09
【问题描述】:

目标:

  1. 在 argparse 中取一个参数,
  2. 测试该参数是否为真
  3. 如果为真,则使用该参数后指定的名称写入文件

例如: 在命令行中:

$ python printfile.py --out_arg fileOutput.txt

... 将在与 printfile.py 相同的目录中生成一个 fileOutput.txt

代码:

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")

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

【问题讨论】:

  • 这里的options.out_33 是什么?
  • print_output实际上是调用吗?
  • 实际上叫什么?
  • 'def parse_arguments()' 的第一行是'options = parse_arguments()'。你要无限递归吗??
  • @MartijnPieters options 指的是我的论点,而 out_33 是我对该特定论点的名称。在这种情况下,--out_33 < filename > 将在命令行中调用,意思是“以 --out_33 格式发送此文件,写入新文件 ”是 options.out_33 没有充分引用命令中传递的文件名那个参数之后的行?

标签: python python-2.7 command-line-arguments argparse sys


【解决方案1】:

您永远不会在输出文件上调用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 是相对路径而不是绝对路径,否则文件将不会在您期望的位置结束。

【讨论】:

    猜你喜欢
    • 2014-01-25
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多