代码写的不是很规范,哪里需要修改的请指正,谢谢
class Myfile_wr_txt:
def __init__(self,filename):
self.filename = filename
self.old_content = ''
self.new_content = ''
self.change_content = ''
def __enter__(self):
self.wr_file = open(self.filename, 'r+', encoding='utf-8')
return self
#文本对象关闭
def __exit__(self, exc_type, exc_val, exc_tb):
self.wr_file.close()
#文本内容读取
def rread(self):
# print(self.wr_file.read()) .read() 只能读取内容一次,必须保存
self.old_content = self.wr_file.read()
print("==" * 5 +"读取"+"==" * 5 )
print(self.old_content)
print("==" * 5 +"内容结束"+"==" * 5 )
#文本内容添加
def wwrite(self,write_content_str):
write_content_str="\n" + write_content_str
self.wr_file.write(write_content_str)
self.new_content = write_content_str
print("++" * 5 +"添加"+"++" * 5 )
print(self.old_content+self.new_content)
print("==" * 5 +"内容结束"+"==" * 5 )
#文本内容修改
def cchange(self,change_content):
self.change_content = "\n"+change_content
self.change_content = self.old_content+self.change_content
#把“r+”改成“w+”,用.write()才能覆盖原本内容
self.wr_file = open(self.filename, 'w+', encoding='utf-8')
self.wr_file.write(self.change_content)
self.wr_file = open(self.filename, 'r+', encoding='utf-8')
print("++" * 5 + "修改后内容" + "++" * 5)
print(self.change_content)
print("==" * 5 + "内容结束" + "==" * 5)
#类中的文本内容清空,否则会出现多余内容
def close_file_content(self):
self.old_content = ''
self.new_content = ''
self.change_content = ''
if __name__ == '__main__':
filename = 'testfile.txt'
file = Myfile_wr_txt(filename)
with file as f:
f.rread()
f.wwrite("诗人李白")
f.cchange("诗人杜甫")
f.cchange("诗人诗圣")
f.close_file_content()
结果:
==========读取==========
静夜思
床前明月光,
疑是地上霜。
举头望明月,
低头思故乡
==========内容结束==========
++++++++++添加++++++++++
静夜思
床前明月光,
疑是地上霜。
举头望明月,
低头思故乡
诗人李白
==========内容结束==========
++++++++++修改后内容++++++++++
静夜思
床前明月光,
疑是地上霜。
举头望明月,
低头思故乡
诗人杜甫
==========内容结束==========
++++++++++修改后内容++++++++++
静夜思
床前明月光,
疑是地上霜。
举头望明月,
低头思故乡
诗人诗圣
==========内容结束==========