48 lines
1.8 KiB
Python
48 lines
1.8 KiB
Python
import os
|
|
from pathlib import Path
|
|
def write_file(file_path: str, content: str) -> str:
|
|
"""
|
|
Write content to a file, creating directories if they do not exist.
|
|
If the file already exists, it will be overwritten.
|
|
:param file_path: Path to the file to write to.
|
|
:param content: Content to write to the file.
|
|
:return: True if the file was written successfully, False otherwise.
|
|
"""
|
|
# Check if the file path is absolute, if not, append to project root
|
|
if not os.path.isabs(file_path):
|
|
file_path = os.path.join(Path(__file__).resolve().parent.parent, file_path)
|
|
dir_path = os.path.dirname(file_path)
|
|
print(f"{dir_path}")
|
|
|
|
# Create the directory if it doesn't exist
|
|
if not os.path.exists(dir_path):
|
|
try:
|
|
os.makedirs(dir_path)
|
|
except OSError as e:
|
|
print(f"Error creating directory {dir_path}: {e}")
|
|
return "Error creating directory, files not written"
|
|
|
|
try:
|
|
with open(file_path, 'w') as f:
|
|
f.write(content)
|
|
return "file written successfully"
|
|
except IOError as e:
|
|
print(f"Error writing to file {file_path}: {e}")
|
|
return f"Error writing to file {file_path}: {e}"
|
|
|
|
def write_file_batch(file_paths: list[str], contents: list[str]) -> list[bool]:
|
|
"""
|
|
Write multiple files in batch.
|
|
:param file_paths: List of file paths to write to.
|
|
:param contents: List of contents to write to the files.
|
|
:return: List of booleans indicating success or failure for each file.
|
|
"""
|
|
results = []
|
|
for file_path, content in zip(file_paths, contents):
|
|
result = write_file(file_path, content)
|
|
results.append(result)
|
|
return results
|
|
|
|
if __name__ == "__main__":
|
|
|
|
write_file(Path("test_data/output/test.txt"), "test") |