-1

The goal:

  1. take an argument in argparse,
  2. test if that argument is true
  3. if true, write a file with the name specified after that argument

Eg: in the command line:

$ python printfile.py --out_arg fileOutput.txt

... would produce a fileOutput.txt in the same directory as printfile.py

Code:

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

Yet, when I call print_output from def main() -not shown- passing in my tuple of interest (seqID, seq, comm), no file is written, and no error message given. Is it the argparse arguments not storing the inputed file as the dest? Is it the use of a file handle when trying write?

Thomas Matthew
  • 2,826
  • 4
  • 34
  • 58

1 Answers1

2

You never call close on the output file. Python's writing is buffered to some degree, and as per the doc if you don't call flush or close you're not guaranteed to have all the output in the file (or a file at all for short ones).

You should always do file IO using the with open() as ofile: syntax to ensure the file is properly flushed/closed:

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

Of course, all of this assumes you're actually calling print_output somewhere, which your code doesn't show. And that options.out_33 is a relative path and not an absolute one, otherwise the file won't wind up where you expect it to.

aruisdante
  • 8,875
  • 2
  • 30
  • 37