Skip to content

Commit 54a6c07

Browse files
committed
add option to treat strings as content only
1 parent 340a806 commit 54a6c07

1 file changed

Lines changed: 16 additions & 1 deletion

File tree

pkg/src/fileex/file.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ def open_file(
6262
def content(
6363
file: FileLike,
6464
*,
65+
path_can_be_str: bool,
6566
output: Literal["str"] = "str",
6667
encoding: str = "utf-8",
6768
errors: str = "strict",
@@ -72,6 +73,7 @@ def content(
7273
def content(
7374
file: FileLike,
7475
*,
76+
path_can_be_str: bool,
7577
output: Literal["bytes"],
7678
encoding: str = "utf-8",
7779
errors: str = "strict",
@@ -81,6 +83,7 @@ def content(
8183
def content(
8284
file: FileLike,
8385
*,
86+
path_can_be_str: bool = True,
8487
output: Literal["str", "bytes"] = "str",
8588
encoding: str = "utf-8",
8689
errors: str = "strict",
@@ -92,6 +95,18 @@ def content(
9295
----------
9396
file
9497
File-like input to get content from.
98+
- If an `os.PathLike` object is provided, it is interpreted as the path to the file.
99+
- If a string is provided and `path_can_be_str` is True, it is interpreted
100+
as the content of the file unless it is a valid existing file path,
101+
in which case it is treated as the path to the file.
102+
- If a string is provided and `path_can_be_str` is False,
103+
it is always treated as the content of the file.
104+
- If a bytes-like object is provided, it is interpreted as the content of the file.
105+
- If an object with a `read()` method is provided, it is treated as a file-like object.
106+
path_can_be_str
107+
If True, strings are checked to see if they are valid existing file paths.
108+
If so, they are treated as file paths; otherwise, as file content.
109+
If False, strings are always treated as file content.
95110
output
96111
Output type, either 'str' or 'bytes'.
97112
encoding
@@ -130,7 +145,7 @@ def return_from_str(s: str) -> str | bytes:
130145

131146
# String: check if path or content
132147
if isinstance(file, str):
133-
if fileex.path.is_path(file):
148+
if path_can_be_str and fileex.path.is_path(file):
134149
return return_from_bytes(Path(file).read_bytes())
135150
return return_from_str(file)
136151

0 commit comments

Comments
 (0)