FoundationAgents/MetaGPT · error · ValueError

The file '{file_name}' is empty. Please use the append metho

Error message

The file '{file_name}' is empty. Please use the append method to add content.

What it means

Raised by Editor._edit_file_by_replace when to_replace is empty/whitespace-only AND the target file's content is also empty after stripping. The tool detects the caller attempted a 'match empty string' replace against an empty file and steers them to the append API, which is the correct way to add content to an empty file.

Source

Thrown at metagpt/tools/libs/editor.py:887

        NOTE:
            This tool is exclusive. If you use this tool, you cannot use any other commands in the current response.
            If you need to use it multiple times, wait for the next turn.
        """
        # FIXME: support replacing *all* occurrences

        if to_replace == new_content:
            raise ValueError("`to_replace` and `new_content` must be different.")

        # search for `to_replace` in the file
        # if found, replace it with `new_content`
        # if not found, perform a fuzzy search to find the closest match and replace it with `new_content`
        file_name = self._try_fix_path(file_name)
        with file_name.open("r") as file:
            file_content = file.read()

        if to_replace.strip() == "":
            if file_content.strip() == "":
                raise ValueError(f"The file '{file_name}' is empty. Please use the append method to add content.")
            raise ValueError("`to_replace` must not be empty.")

        if file_content.count(to_replace) > 1:
            raise ValueError(
                "`to_replace` appears more than once, please include enough lines to make code in `to_replace` unique."
            )
        start = file_content.find(to_replace)
        if start != -1:
            # Convert start from index to line number
            start_line_number = file_content[:start].count("\n") + 1
            end_line_number = start_line_number + len(to_replace.splitlines()) - 1
        else:

            def _fuzzy_transform(s: str) -> str:
                # remove all space except newline
                return re.sub(r"[^\S\n]+", "", s)

            # perform a fuzzy search (remove all spaces except newlines)

View on GitHub (pinned to 11cdf466d0)

Solutions

  1. Use the append mode (or insert at line 1) to add initial content to an empty file
  2. Write initial content at creation time rather than replace-after-create

Example fix

// before
editor.create_file('a.py')
editor.edit_file_by_replace('a.py', to_replace='\n', new_content='x = 1\n')  # ValueError: file is empty

// after
editor.create_file('a.py')
editor.append_file('a.py', 'x = 1\n')  # or write content via insert at line 1
Defensive patterns

Strategy: validation

Validate before calling

content = Path(file_name).read_text()
if content.strip() == '':
    editor.append_file(file_name, new_content)  # correct API for empty files
else:
    editor.edit_file_by_replace(file_name, to_replace, new_content)

Type guard

def file_is_empty(p: str) -> bool:
    return Path(p).read_text().strip() == ''

Try / catch

try:
    editor.edit_file_by_replace(path, to_replace, new_content)
except ValueError as e:
    if 'is empty' in str(e):
        editor.append_file(path, new_content)
    else:
        raise

Prevention

When it happens

Trigger: editor.edit_file_by_replace(path, to_replace='', new_content=c) on a zero-byte or whitespace-only file (e.g. one just created by create_file, which writes a single newline).

Common situations: Agents immediately 'replacing' into freshly created files; create_file writes '\n' so a brand-new file is empty-by-strip and hits this path; bootstrap flows that should append instead.

Related errors


AI-assisted analysis of FoundationAgents/MetaGPT@11cdf466d0 (2026-08-14). Data as JSON: /api/errors/d18259977fec6da7. Report an issue: GitHub.