File objects¶
When you want to declare some types of files, you can use Path.
However, in some cases you may need to have access to a file-like object, and then you can use these special File types.
These objects can be imported from typer directly:
from typer import FileBinaryRead, FileBinaryWrite, FileText, FileTextWrite
typer.FileText
¶
Bases: TextIOWrapper
Gives you a file-like object for reading text, and you will get a str data from it.
The default mode of this class is mode="r".
Example
from typing import Annotated
import typer
app = typer.Typer()
@app.command()
def main(config: Annotated[typer.FileText, typer.Option()]):
for line in config:
print(f"Config line: {line}")
if __name__ == "__main__":
app()
typer.FileTextWrite
¶
Bases: FileText
You can use this class for writing text. Alternatively, you can use FileText with mode="w".
The default mode of this class is mode="w".
Example
from typing import Annotated
import typer
app = typer.Typer()
@app.command()
def main(config: Annotated[typer.FileTextWrite, typer.Option()]):
config.write("Some config written by the app")
print("Config written")
if __name__ == "__main__":
app()
typer.FileBinaryRead
¶
Bases: BufferedReader
You can use this class to read binary data, receiving bytes.
The default mode of this class is mode="rb".
It is useful for reading binary files like images:
Example
from typing import Annotated
import typer
app = typer.Typer()
@app.command()
def main(file: Annotated[typer.FileBinaryRead, typer.Option()]):
processed_total = 0
for bytes_chunk in file:
# Process the bytes in bytes_chunk
processed_total += len(bytes_chunk)
print(f"Processed bytes total: {processed_total}")
if __name__ == "__main__":
app()
typer.FileBinaryWrite
¶
Bases: BufferedWriter
You can use this class to write binary data: you pass bytes to it instead of strings.
The default mode of this class is mode="wb".
It is useful for writing binary files like images:
Example
from typing import Annotated
import typer
app = typer.Typer()
@app.command()
def main(file: Annotated[typer.FileBinaryWrite, typer.Option()]):
first_line_str = "some settings\n"
# You cannot write str directly to a binary file; encode it first
first_line_bytes = first_line_str.encode("utf-8")
# Then you can write the bytes
file.write(first_line_bytes)
# This is already bytes, it starts with b"
second_line = b"la cigüeña trae al niño"
file.write(second_line)
print("Binary file written")
if __name__ == "__main__":
app()