On this page
argparse.FileType
Prev: argparse.BooleanOptionalAction | Up: argparse | Next: argparse.HelpFormatter
Rel: argparse.Action, argparse.ArgumentDefaultsHelpFormatter, argparse.ArgumentError, argparse.ArgumentParser
Ref: docs.python.org — argparse.FileType
Tags: #public #python3 #stdlib #argparse
Import
import argparse
from argparse import FileType
Signature & Overview
argparse.FileType(mode='r', bufsize=-1, encoding=None, errors=None)
Deprecated factory for creating file object types Instances of FileType are typically passed as type= arguments to the ArgumentParser add_argument() method.
Usage
import argparse
from pathlib import Path
import tempfile
with tempfile.TemporaryDirectory() as tmp:
src = Path(tmp) / "in.txt"
src.write_text("hello", encoding="utf-8")
p = argparse.ArgumentParser()
p.add_argument("file", type=argparse.FileType("r", encoding="utf-8"))
args = p.parse_args([str(src)])
try:
assert args.file.read() == "hello"
finally:
args.file.close()
Gotchas
- Opens files eagerly during
parse_args(): If a later argument fails validation, an output file opened withFileType("w")may already be truncated on disk. - Often better to accept
type=Path: Open the file yourself inside awithblock after parsing succeeds.
REPL Inspect
from argparse import FileType
help(FileType)
Linked from
Related notes
- tuts/python3/stdlib_module/argparse/BooleanOptionalAction Linked here; links to this page; shared tags: #argparse, #stdlib
- tuts/python3/stdlib_module/argparse/HelpFormatter Linked here; links to this page; shared tags: #argparse, #stdlib
- tuts/python3/stdlib_module/argparse Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/argparse/Action Linked here; shared tags: #argparse, #stdlib
- tuts/python3/stdlib_module/argparse/ArgumentDefaultsHelpFormatter Linked here; shared tags: #argparse, #stdlib
- tuts/python3/stdlib_module/argparse/ArgumentError Linked here; shared tags: #argparse, #stdlib
- tuts/python3/stdlib_module/argparse/ArgumentParser Linked here; shared tags: #argparse, #stdlib
- tuts/python3/stdlib_module/argparse/ArgumentTypeError shared tags: #argparse, #stdlib
- tuts/python3/stdlib_module/argparse/MetavarTypeHelpFormatter shared tags: #argparse, #stdlib
- tuts/python3/stdlib_module/argparse/Namespace shared tags: #argparse, #stdlib