Skip to content

Instantly share code, notes, and snippets.

@pdarragh
Last active February 3, 2021 20:35
Show Gist options
  • Save pdarragh/12954fdad7e557cffa19bdb988369d4d to your computer and use it in GitHub Desktop.
Save pdarragh/12954fdad7e557cffa19bdb988369d4d to your computer and use it in GitHub Desktop.
Simple Python I/O using argparse
import argparse
from pathlib import Path
"""
Run this by doing:
$ python3 better_io.py /path/to/file
This version uses the `type` parameter of the `add_argument` function to pass
the string given on the command line into a `pathlib.Path` object. These are
easier to use, and it also guarantees that what we got was a properly formatted
string.
"""
def print_file_contents(filename: Path):
print(filename.read_text())
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('file_name', type=Path, help='the path to the file')
args = parser.parse_args()
print_file_contents(args.file_name)
import argparse
"""
Run this by doing:
$ python3 easy_io.py /path/to/file
"""
def print_file_contents(filename):
with open(filename) as f:
print(f.read())
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('file_name', help='the path to the file')
args = parser.parse_args()
print_file_contents(args.file_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment