I've been using argparse and have problems writing the output into a file with an optional output argument for argparse (--outfile). I always get an empty file when using the --outfile argument, but using standard output works. I am quite new to Python so there may be something obvious that I am missing.
I'm actually working on a more complex program that is a bit too long to share, so I created a simple dummy example that gets the same error.
This is the code:
import argparse
import sys
def print_content(file):
for lines in file:
print(f'This is the content: {lines}')
def create_argument_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser('printer',
description='a commandline tool that prints the content of a file')
parser.add_argument('input_file',
type=argparse.FileType(encoding='utf-8'),
default=[sys.stdin],
metavar='FILE')
parser.add_argument('--outfile', '-o',
type=argparse.FileType('w', encoding='utf-8'),
default=[sys.stdout],
metavar='FILE')
parser.add_argument('--print',
help='if present, prints the content of the file',
action='store_true')
return parser
def main():
parser = create_argument_parser()
args = parser.parse_args()
if args.print:
print_content(args.input_file)
if __name__ == '__main__':
main()
If I use standard output as below it works:
$ python program.py text.txt --print < output.txt
However, if I use the --outfile argument, the file is created but remains empty.
$ python program.py text.txt --print --outfile output.txt
What am I missing? (I use Python 3.8.5.)