封装方法1:定义一个类,实现读文件、写文件的方法

本文介绍了一个用于读取和写入文件的Python类设计。该类提供了读取和写入文件的方法,支持路径设置和多种文件操作模式。通过实例化该类并调用其方法,可以方便地进行文件读写操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

定义一个类,实现读文件、写文件的方法
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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值