How can I implement this code? #88572
-
Bodyhttps://github.com/PyDOS8/PyDOS8/blob/main/src/kernel/Kernel.py Guidelines
|
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 7 replies
-
I Don't know whether this would help when opening a file with the with block in Python you Don't need to close it annually, like you did |
Beta Was this translation helpful? Give feedback.
-
This code defines functions for basic file system operations using a JSON file named "FS.json." So you could implement this in a file system like project. |
Beta Was this translation helpful? Give feedback.
-
Hope this helps..... import json
import os
class JSONFileSystem:
def __init__(self, file_name='FS.json'):
self.file_name = file_name
self.file_system = self.load_file_system()
def load_file_system(self):
try:
with open(self.file_name, 'r') as file:
return json.load(file)
except FileNotFoundError:
return {}
def save_file_system(self):
with open(self.file_name, 'w') as file:
json.dump(self.file_system, file, indent=2)
def create_file(self, file_name, content):
self.file_system[file_name] = content
self.save_file_system()
def read_file(self, file_name):
return self.file_system.get(file_name, 'File not found')
def delete_file(self, file_name):
if file_name in self.file_system:
del self.file_system[file_name]
self.save_file_system()
return f'{file_name} deleted successfully'
else:
return f'{file_name} not found'
# A simple example usage
file_system = JSONFileSystem()
file_system.create_file('example.json', {'key': 'value'})
print(file_system.read_file('example.json'))
print(file_system.delete_file('example.json'))
print(file_system.read_file('example.json')) So I just created a reusable json file system class. So you could have this in a jsonfilesystem.py file and import it in your Projects to implement It. import jsonfilesystem as jfs |
Beta Was this translation helpful? Give feedback.
Hope this helps.....