How to open file using argparse?

PythonArgparse

Python Problem Overview


I want to open file for reading using argparse. In cmd it must look like: my_program.py /filepath

That's my try:

parser = argparse.ArgumentParser()
parser.add_argument('file', type = file)
args = parser.parse_args()

Python Solutions


Solution 1 - Python

Take a look at the documentation: https://docs.python.org/3/library/argparse.html#type

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('file', type=argparse.FileType('r'))
args = parser.parse_args()

print(args.file.readlines())

Solution 2 - Python

The type of the argument should be string (which is default anyway). So make it like this:

parser = argparse.ArgumentParser()
parser.add_argument('filename')
args = parser.parse_args()
with open(args.filename) as file:
  # do stuff here

Solution 3 - Python

In order to have the file closed gracefully, you can combine argparse.FileType with the "with" statement

# ....

parser.add_argument('file', type=argparse.FileType('r'))
args = parser.parse_args()

with args.file as file:
    print file.read()

--- update ---

Oh, @Wernight already said that in comments

Solution 4 - Python

I'll just add the option to use pathlib:

import argparse, pathlib

parser = argparse.ArgumentParser()
parser.add_argument('file', type=pathlib.Path)
args = parser.parse_args()

with args.file.open('r') as file:
    print(file.read())

Solution 5 - Python

TL; DR

parser.add_argument(
    '-f', '--file',
    help='JSON input file',
    type=argparse.FileType('r'),
)

Description

Simple command line script to reformat JSON files

reformat-json \
    -f package.json \
    --indent=2 \
    --sort-keys \
    --output=sorted_package.json

can be code in Python as follows

#!/usr/bin/env python3

import argparse, json, sys

EXIT_SUCCESS = 0
EXIT_FAILURE = 1

def main():
    parser = argparse.ArgumentParser()

    parser.add_argument(
        '-f', '--file',
        help='JSON input file',
        type=argparse.FileType('r'),
    )

    parser.add_argument(
        '-i', '--indent',
        help='Non-negative integer indent level',
        type=int
    )

    parser.add_argument(
        '-o', '--output',
        help='Write JSON into output file',
        type=argparse.FileType('w'),
    )

    parser.add_argument(
        '-s', '--sort-keys',
        action='store_true',
        help='Sort output JSON by keys',
    )

    args = parser.parse_args()

    if not args.file:
        parser.print_usage()
        return sys.exit(EXIT_FAILURE)

    gson = json.dumps(
        json.load(args.file),
        indent=args.indent,
        sort_keys=args.sort_keys
    )

    args.file.close()

    if args.output:
        args.output.write(gson)
        args.output.write('\n')
        args.output.close()
    else:
        print(gson)

    return sys.exit(EXIT_SUCCESS)

if __name__ == '__main__':
    main()

Solution 6 - Python

This implementation allows the "file name" parameter to be optional, as well as giving a short description if and when the user enters the -h or --help argument.

parser = argparse.ArgumentParser(description='Foo is a program that does things')
parser.add_argument('filename', nargs='?')
args = parser.parse_args()

if args.filename is not None:
    print('The file name is {}'.format(args.filename))
else:
    print('Oh well ; No args, no problems')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnuT707View Question on Stackoverflow
Solution 1 - Pythonilent2View Answer on Stackoverflow
Solution 2 - PythonwimView Answer on Stackoverflow
Solution 3 - PythonMingView Answer on Stackoverflow
Solution 4 - PythonThomas AhleView Answer on Stackoverflow
Solution 5 - PythonJP VenturaView Answer on Stackoverflow
Solution 6 - PythonyPhilView Answer on Stackoverflow