1 Star 0 Fork 0

巧克力ovo/PythonLearn

Create your Gitee Account
Explore and code with more than 13.5 million developers,Free private repositories !:)
Sign up
文件
This repository doesn't specify license. Please pay attention to the specific project description and its upstream code dependency when using it.
Clone or Download
6-2.py 3.29 KB
Copy Edit Raw Blame History
wlt authored 27 days ago . 6
#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()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/chocolate-ovo/python-learn.git
git@gitee.com:chocolate-ovo/python-learn.git
chocolate-ovo
python-learn
PythonLearn
master

Search