使用 Python 实现一个文件系统模拟类
描述内容: 我们将使用 Python 实现一个简单的文件系统模拟类。这个类将允许用户创建目录、创建文件、删除文件、列出目录内容等基本操作。我们将使用字典来模拟文件系统的层级结构。
代码部分:
实例
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: []
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: []
代码解析:
__init__
方法初始化文件系统,创建一个根目录/
。mkdir
方法用于创建目录。它通过遍历路径的每一部分来创建嵌套的字典结构。touch
方法用于创建文件。它将路径的最后一部分作为文件名,并在相应的目录中创建一个键值对。ls
方法用于列出目录内容。它遍历路径并返回目录中的键(即文件或子目录的名称)。rm
方法用于删除文件。它遍历路径并删除指定的文件。
输出结果:
实例
['file.txt']
[]
[]
点我分享笔记