Implement a file system simulation class using Python

Document 对象参考手册Python3 Examples

Description: We will use Python to implement a simple file system simulation class. This class will allow users to perform basic operations such as creating directories, creating files, deleting files, and listing directory contents. We will use dictionaries to simulate the hierarchical structure of the file system.

Code section:

Example

class FileSystem:
    def __init__(self):
        self.root = {'/': {}}

    def mkdir(self, path):
        current = self.root['/']
        parts = path.strip('/').split('/')
        for part in parts:
            if part not in current:
                current[part] = {}
            current = current[part]

    def touch(self, path):
        current = self.root['/']
        parts = path.strip('/').split('/')
        filename = parts[-1]
        dir_path = parts[:-1]
        for part in dir_path:
            if part not in current:
                current[part] = {}
            current = current[part]
        current[filename] = None

    def ls(self, path):
        current = self.root['/']
        parts = path.strip('/').split('/')
        for part in parts:
            if part not in current:
                return f"Path '{path}' not found."
            current = current[part]
        if isinstance(current, dict):
            return list(current.keys())
        else:
            return [parts[-1]]

    def rm(self, path):
        current = self.root['/']
        parts = path.strip('/').split('/')
        filename = parts[-1]
        dir_path = parts[:-1]
        for part in dir_path:
            if part not in current:
                return f"Path '{path}' not found."
            current = current[part]
        if filename in current:
            del current[filename]
            return f"File '{filename}' deleted."
        else:
            return f"File '{filename}' not found."

# Example usage
fs = FileSystem()
fs.mkdir('/home/user')
fs.touch('/home/user/file.txt')
print(fs.ls('/home/user'))  # Output: ['file.txt']
fs.rm('/home/user/file.txt')
print(fs.ls('/home/user'))  # Output: []

Code explanation:

  1. __init__The method initializes the file system and creates a root directory./。
  2. mkdirThe method is used to create directories. It traverses each part of the path to create a nested dictionary structure.
  3. touchThe method is used to create files. It takes the last part of the path as the file name and creates a key-value pair in the corresponding directory.
  4. lsThe method is used to list directory contents. It traverses the path and returns the keys in the directory (i.e., the names of files or subdirectories).
  5. rmThe method is used to delete files. It traverses the path and deletes the specified file.

Output:

Example

['file.txt']
[]

Document 对象参考手册Python3 Examples

Other Extensions