python_utils/utils/read_wirte_file_utils.py
M. A. Reza 0c471c8fb5 update
2025-12-01 17:04:57 +03:30

40 lines
1.1 KiB
Python

import json
from pathlib import Path
def serialize_sets(obj):
if isinstance(obj, set):
return list(obj)
raise TypeError
def write_to_file(content, file_path: Path, json_dumps=False, indent=None):
file_path.parent.mkdir(parents=True, exist_ok=True)
with open(file_path, mode="w") as f:
if json_dumps:
return f.write(
json.dumps(
content, indent=indent, ensure_ascii=False, default=serialize_sets
)
)
return f.write(content)
def append_to_file(content: str, file_path: Path):
file_path.parent.mkdir(parents=True, exist_ok=True)
with open(file_path, mode="a") as f:
return f.write(content)
def write_binary_to_file(content, file_path: Path):
file_path.parent.mkdir(parents=True, exist_ok=True)
with open(file_path, mode="wb") as f:
return f.write(content)
def read_file(file_path, json_loads):
with open(file_path, "r") as file:
if json_loads:
return json.loads(file.read())
return file.read()