4
@Time : 2023/9/4 15:40:40
7
@Describe : General file operations.
9
from pathlib import Path
13
from metagpt.logs import logger
14
from metagpt.utils.exceptions import handle_exception
18
"""A general util for file operations."""
20
CHUNK_SIZE = 64 * 1024
24
async def write(cls, root_path: Path, filename: str, content: bytes) -> Path:
25
"""Write the file content to the local specified path.
28
root_path: The root path of file, such as "/data".
29
filename: The name of file, such as "test.txt".
30
content: The binary content of file.
33
The full filename of file, such as "/data/test.txt".
36
Exception: If an unexpected error occurs during the file writing process.
38
root_path.mkdir(parents=True, exist_ok=True)
39
full_path = root_path / filename
40
async with aiofiles.open(full_path, mode="wb") as writer:
41
await writer.write(content)
42
logger.debug(f"Successfully write file: {full_path}")
47
async def read(cls, file_path: Path, chunk_size: int = None) -> bytes:
48
"""Partitioning read the file content from the local specified path.
51
file_path: The full file name of file, such as "/data/test.txt".
52
chunk_size: The size of each chunk in bytes (default is 64kb).
55
The binary content of file.
58
Exception: If an unexpected error occurs during the file reading process.
60
chunk_size = chunk_size or cls.CHUNK_SIZE
61
async with aiofiles.open(file_path, mode="rb") as reader:
64
chunk = await reader.read(chunk_size)
68
content = b"".join(chunks)
69
logger.debug(f"Successfully read file, the path of file: {file_path}")