Fetch the repository succeeded.
#rb 以二进制打开文件,在读取时不会进行编码转换
#wb 以二进制打开文件,在写入时不会进行编码转换
#rb+ 以二进制打开文件,读写模式,文件指针在文件开头
#wb+ 以二进制打开文件,读写模式,文件指针在文件开头
#ab 以二进制打开文件,读写模式,文件指针在文件末尾
#ab+ 以二进制打开文件,读写模式,文件指针在文件末尾
def create_write_file():
filename = input("请输入文件名:")
if not filename:
print("文件名不能为空!")
return
content = input("请输入内容:")
if not content:
print("内容不能为空!")
return
try:
with open(filename, 'w', encoding='utf-8') as f:
f.write(content)
print(f"文件{filename}已创建并写入内容")
except IOError:
print(f"创建文件{filename}时发生错误")
except Exception as e:
print(f"发生了其他错误:{e}")
def read_file():
filename = input("请输入文件名:")
if not filename:
print("文件名不能为空!")
return
try:
with open(filename, 'r', encoding='utf-8') as f:
content = f.read()
print(content)
except FileNotFoundError:
print(f"文件{filename}不存在")
except IOError:
print(f"读取文件{filename}时发生错误")
except Exception as e:
print(f"发生了其他错误:{e}")
def append_file():
filename = input("请输入文件名:").strip()
if not filename:
print("文件名不能为空!")
return
import os
if not os.path.exists(filename):
print(f"文件{filename}不存在,无法追加内容")
return
content = input("请输入内容:").strip()
if not content:
print("内容不能为空!")
return
try:
with open(filename, 'a', encoding='utf-8') as f:
f.write(','+content)
print(f"内容已追加到文件{filename}")
except IOError:
print(f"追加文件{filename}时发生错误")
except Exception as e:
print(f"发生了其他错误:{e}")
def delete_file():
filename = input("请输入文件名:")
if not filename:
print("文件名不能为空!")
return
import os
try:
if os.path.exists(filename):
os.remove(filename)
print(f"文件{filename}已删除")
else:
print(f"文件{filename}不存在")
except PermissionError:
print(f"没有权限删除文件{filename}")
except Exception as e:
print(f"发生了其他错误:{e}")
def myNotebook():
while True:
print("简单记事本")
print("1.创建并写入文件")
print("2.读取文件")
print("3.追加文件")
print("4.删除文件")
print("5.退出")
choice=input("请输入你的选择编号:")
if choice == '1':
create_write_file()
elif choice == '2':
read_file()
elif choice == '3':
append_file()
elif choice == '4':
delete_file()
elif choice == '5':
break
else:
print("无效的选择,请重新输入")
if __name__ == "__main__":
myNotebook()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。