我自己写的一点,不知道好不好,但是可以实现上面的问题,欢迎各位交流。
做这个题目,首先你知道怎么打开和关闭文件,并且如何处理意外情况的发生,对于python的一些基础语法,函数定义,判断语句等有一定的认识,欢迎大家一起交流学习,我来抛砖引玉!
import os
import time
def read():
name = input("请输入要处理的文件名:")
if os.path.exists(name):
with open(name, 'r',encoding='utf-8') as f:
print(f.read())
else:
print("这个文件不存在,请确认后输入!")
def write():
name = input("请输入要处理的文件名:")
if os.path.exists(name):
with open(name,'a') as f1:
content = input("请输入你要添加的内容:")
f1.write(content)
with open(name,'r') as f2:
print("打印全部内容,含添加的!")
print(f2.read())
print('-.'*30)
print("打印新添加的内容!")
print(content)
if __name__ == '__main__':
n = int(input("请输入你要处理的类型,读按1,写按2:"))
if n == 1:
read()
time.sleep(5)
else:
write()
time.sleep(5)