1.编写一个模拟记事本的程序,通过在控制台输入指令,实现本地新建文件、打开文件、修改文件和保存文件等功能。
时间: 2024-04-30 22:17:38 浏览: 22
这里给出一个基本的实现思路,具体实现可以根据需求进行修改:
1. 定义一个文件类,包含文件名、文件内容等属性,以及打开、保存等方法。
2. 定义一个文件管理类,包含管理文件的方法,如新建文件、打开文件、修改文件和保存文件等。
3. 在控制台中读取用户输入的指令,根据指令调用文件管理类中对应的方法。
代码如下:
```python
class File:
def __init__(self, name):
self.name = name
self.content = ""
def open(self):
with open(self.name, "r") as f:
self.content = f.read()
def save(self):
with open(self.name, "w") as f:
f.write(self.content)
def modify(self, new_content):
self.content = new_content
class FileManager:
def __init__(self):
self.files = {}
def new_file(self, name):
if name in self.files:
print("File already exists!")
else:
file = File(name)
self.files[name] = file
print("File created.")
def open_file(self, name):
if name not in self.files:
print("File does not exist!")
else:
self.files[name].open()
print("File opened.")
def modify_file(self, name, new_content):
if name not in self.files:
print("File does not exist!")
else:
self.files[name].modify(new_content)
print("File modified.")
def save_file(self, name):
if name not in self.files:
print("File does not exist!")
else:
self.files[name].save()
print("File saved.")
manager = FileManager()
while True:
command = input("Enter command (new/open/modify/save/exit): ")
if command == "new":
name = input("Enter file name: ")
manager.new_file(name)
elif command == "open":
name = input("Enter file name: ")
manager.open_file(name)
elif command == "modify":
name = input("Enter file name: ")
new_content = input("Enter new content: ")
manager.modify_file(name, new_content)
elif command == "save":
name = input("Enter file name: ")
manager.save_file(name)
elif command == "exit":
break
else:
print("Invalid command!")
```
运行程序后,在控制台输入指令即可实现相应的功能。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)