Last active
February 3, 2021 20:35
-
-
Save pdarragh/12954fdad7e557cffa19bdb988369d4d to your computer and use it in GitHub Desktop.
Simple Python I/O using argparse
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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