Skip to content

Commit 154a388

Browse files
committed
Update file.py
1 parent 8ce238f commit 154a388

1 file changed

Lines changed: 46 additions & 1 deletion

File tree

pkg/src/fileex/file.py

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
from pathlib import Path
2-
from typing import IO
2+
from typing import IO, Literal, Type
33
import io
44

55
import fileex
6+
from fileex.typing import FileLike
67

78

89
def open_file(
@@ -54,3 +55,47 @@ def open_file(
5455
raise TypeError(
5556
f"Expected str, bytes, or pathlib.Path, got {type(source).__name__}"
5657
)
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

Comments
 (0)