|
1 | 1 | from pathlib import Path |
2 | | -from typing import IO |
| 2 | +from typing import IO, Literal, Type |
3 | 3 | import io |
4 | 4 |
|
5 | 5 | import fileex |
| 6 | +from fileex.typing import FileLike |
6 | 7 |
|
7 | 8 |
|
8 | 9 | def open_file( |
@@ -54,3 +55,47 @@ def open_file( |
54 | 55 | raise TypeError( |
55 | 56 | f"Expected str, bytes, or pathlib.Path, got {type(source).__name__}" |
56 | 57 | ) |
| 58 | + |
| 59 | + |
| 60 | +def content( |
| 61 | + file: FileLike, |
| 62 | + *, |
| 63 | + output: Literal["str", "bytes"] = "str", |
| 64 | + encoding: str = "utf-8" |
| 65 | +) -> str | bytes: |
| 66 | + """Get the content of a file-like input. |
| 67 | +
|
| 68 | + Parameters |
| 69 | + ---------- |
| 70 | + file |
| 71 | + File-like input to get content from. |
| 72 | + output |
| 73 | + Output type, either 'str' or 'bytes'. |
| 74 | + encoding |
| 75 | + Encoding used to decode the file if it is provided as bytes or Path, |
| 76 | + and output is 'str'. |
| 77 | +
|
| 78 | + Returns |
| 79 | + ------- |
| 80 | + file_content |
| 81 | + Content of the file as a string or bytes. |
| 82 | + """ |
| 83 | + if output not in ("str", "bytes"): |
| 84 | + raise ValueError("output must be either 'str' or 'bytes'") |
| 85 | + |
| 86 | + if isinstance(file, str): |
| 87 | + content_bytes = ( |
| 88 | + Path(file).read_bytes() |
| 89 | + if fileex.path.is_path(file) else |
| 90 | + file.encode(encoding) |
| 91 | + ) |
| 92 | + elif isinstance(file, bytes): |
| 93 | + content_bytes = file |
| 94 | + elif isinstance(file, Path): |
| 95 | + content_bytes = file.read_bytes() |
| 96 | + else: |
| 97 | + raise TypeError( |
| 98 | + f"Expected str, bytes, or pathlib.Path, got {type(file).__name__}" |
| 99 | + ) |
| 100 | + |
| 101 | + return content_bytes.decode(encoding) if output == "str" else content_bytes |
0 commit comments