MediumStateful DesignPython 3

In-memory Filesystem

Model directory and file state with predictable path normalization and listing behavior.

35m3 sample tests6 hidden tests

Implement a tiny filesystem with directories and files.

Requirements

  • Define FileSystem.
  • mkdir(path) creates directories recursively. Creating an existing directory is a no-op.
  • write_file(path, content) writes or overwrites a file. Parent directory must exist (the root / always exists, so /file needs no prior mkdir).
  • Writing to an existing directory raises IsADirectoryError; it must not delete that directory's contents.
  • read_file(path) returns file content.
  • ls(path) returns sorted child names for a directory, or [filename] for a file.
  • Missing paths raise FileNotFoundError.
  • read_file on a directory raises IsADirectoryError.
  • If a path component is a file, operations that would traverse through it (mkdir or write_file under that path) raise NotADirectoryError.

Example

python
1fs = FileSystem() 2fs.mkdir("/docs") 3fs.write_file("/docs/readme.md", "hello") 4assert fs.ls("/") == ["docs"] 5assert fs.ls("/docs/readme.md") == ["readme.md"] 6assert fs.read_file("/docs/readme.md") == "hello"

Constraints

  • Use standard-library Python only.
  • Normalize repeated slashes and trailing slashes.

Editor