Simulating a file system with a Python class
Description: we will use Python to implement a simple file system simulation class. This class will allow users to create directories, create files, delete files, list directory contents, and other basic operations. We will use a dictionary to simulate the hierarchical structure of the file system.
The code:
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'
)
(
fs.
ls
(
'/home/user'
)
)
Output: ['file.txt']
fs.
rm
(
'/home/user/file.txt'
)
(
fs.
ls
(
'/home/user'
)
)
Output: []
Code analysis:
__init__method initializes the file system, creating a root directory/。mkdirmethod is used to create a directory. It creates a nested dictionary structure by traversing each part of the path.touchmethod is used to create a file. It uses the last part of the path as the file name and creates a key-value pair in the corresponding directory.lsmethod 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).rmmethod is used to delete a file. It traverses the path and deletes the specified file.
Output result:
Example
[
'file.txt'
]
[
]
Python3 Examples