diff --git a/autogpt/commands/file_operations.py b/autogpt/commands/file_operations.py index 9999fccf..05f06088 100644 --- a/autogpt/commands/file_operations.py +++ b/autogpt/commands/file_operations.py @@ -142,8 +142,7 @@ def write_to_file(filename: str, text: str) -> str: return "Error: File has already been updated." try: directory = os.path.dirname(filename) - if not os.path.exists(directory): - os.makedirs(directory) + os.makedirs(directory, exist_ok=True) with open(filename, "w", encoding="utf-8") as f: f.write(text) log_operation("write", filename) @@ -167,6 +166,8 @@ def append_to_file(filename: str, text: str, should_log: bool = True) -> str: str: A message indicating success or failure """ try: + directory = os.path.dirname(filename) + os.makedirs(directory, exist_ok=True) with open(filename, "a") as f: f.write(text) @@ -236,6 +237,8 @@ def download_file(url, filename): filename (str): Filename to save the file as """ try: + directory = os.path.dirname(filename) + os.makedirs(directory, exist_ok=True) message = f"{Fore.YELLOW}Downloading file from {Back.LIGHTBLUE_EX}{url}{Back.RESET}{Fore.RESET}" with Spinner(message) as spinner: session = requests.Session() diff --git a/tests/unit/test_file_operations.py b/tests/unit/test_file_operations.py index c3b20d0c..b2760671 100644 --- a/tests/unit/test_file_operations.py +++ b/tests/unit/test_file_operations.py @@ -33,6 +33,7 @@ class TestFileOperations(unittest.TestCase): self.test_file = str(self.workspace.get_path("test_file.txt")) self.test_file2 = "test_file2.txt" self.test_directory = str(self.workspace.get_path("test_directory")) + self.test_nested_file = str(self.workspace.get_path("nested/test_file.txt")) self.file_content = "This is a test file.\n" self.file_logger_logs = "file_logger.txt" @@ -69,21 +70,23 @@ class TestFileOperations(unittest.TestCase): def test_write_to_file(self): new_content = "This is new content.\n" - write_to_file(self.test_file, new_content) - with open(self.test_file, "r") as f: + write_to_file(self.test_nested_file, new_content) + with open(self.test_nested_file, "r") as f: content = f.read() self.assertEqual(content, new_content) def test_append_to_file(self): - with open(self.test_file, "r") as f: - content_before = f.read() - append_text = "This is appended text.\n" - append_to_file(self.test_file, append_text) - with open(self.test_file, "r") as f: + append_to_file(self.test_nested_file, append_text) + with open(self.test_nested_file, "r") as f: content = f.read() - self.assertEqual(content, content_before + append_text) + append_to_file(self.test_nested_file, append_text) + + with open(self.test_nested_file, "r") as f: + content_after = f.read() + + self.assertEqual(content_after, append_text + append_text) def test_delete_file(self): delete_file(self.test_file)