40 lines
1.3 KiB
Python
40 lines
1.3 KiB
Python
import os
|
|
from pathlib import Path
|
|
|
|
class VirtualFileSystem:
|
|
"""
|
|
A simple in-memory virtual file system that stores files as a dictionary.
|
|
Provides methods to write, read, list, and export files to the real filesystem.
|
|
"""
|
|
def __init__(self):
|
|
self.files = {} # dict of filename -> content
|
|
|
|
def write_file(self, name: str, content: str):
|
|
"""
|
|
Write content to a virtual file. Overwrites if the file already exists.
|
|
"""
|
|
self.files[name] = content
|
|
|
|
def read_file(self, name: str) -> str:
|
|
"""
|
|
Read content from a virtual file. Returns empty string if file does not exist.
|
|
"""
|
|
return self.files.get(name, "")
|
|
|
|
def list_files(self):
|
|
"""
|
|
Return a list of all virtual file names.
|
|
"""
|
|
return list(self.files.keys())
|
|
|
|
def export_to_disk(self, base_path: str):
|
|
"""
|
|
Export all virtual files to the real filesystem under the given base_path.
|
|
Creates directories as needed.
|
|
"""
|
|
os.makedirs(base_path, exist_ok=True)
|
|
for name, content in self.files.items():
|
|
file_path = os.path.join(base_path, name)
|
|
os.makedirs(os.path.dirname(file_path), exist_ok=True)
|
|
with open(file_path, "w", encoding="utf-8") as f:
|
|
f.write(content) |