定义一个类,实现读文件、写文件的方法
import os
class ReadAndWrite(object):
def init(self,path):
self.file_path = path
def read_file(self,path=None,mode='r',buffering='utf-8'):
if path is not None:
self.file_path = path
if not (os.path.exists(self.file_path) or os.path.isfile(self.file_path)):
return '文件不存在'
try:
print(self.file_path,mode,buffering)
with open(self.file_path,mode,buffering) as fp:
content = fp.read()
return content
except TypeError:
with open(self.file_path,mode) as fp:
content = fp.read()
return content
except Exception as e:
return e
def write_file(self, path=None, mode='w',buffering='utf-8',write_info=None):
if path is not None:
self.file_path = path
if not (os.path.exists(self.file_path) or os.path.isfile(self.file_path)):
return '文件不存在'
if mode == 'r':
return '文件操作模式不正确'
try:
with open(self.file_path,mode,buffering) as fp:
fp.write(str(write_info))
return True
except TypeError:
with open(self.file_path,mode) as fp:
fp.write(str(write_info))
return True
except Exception as e:
return e
rw = ReadAndWrite(‘D:\python’)
rw = ReadAndWrite(‘D:\python\no.txt’)
r = rw.read_file(path=None,mode=‘r’,buffering=‘utf-8’)
print(‘读文件内容:’,r)
r = rw.write_file(path=None,mode=‘r’,buffering=‘utf-8’)
r = rw.write_file(path=None,mode=‘w’,buffering=‘utf-8’)
print(‘写文件内容:’,r)