day 9 作业:封装文件操作

import json

1.文本文件相关的

def get_text_file_content(file_path):
    """
    获取文本文件的内容
    :param file_path:需要获取的文件路径
    :return: 文件的内容
    """
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            return f.read()
    except FileNotFoundError:
        print('Error:文件不存在!!!')
        return None
def write_text_file(content, file_path):
    """
    将数据写到指定的文本文件中
    :param content: 需要写入的内容
    :param file_path: 文件路径
    :return: 返回写操作是否成功
    """
    while True:
        try:
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)
                return True
        except TypeError:
            print('内容必须是字符串')
            return False

2.json 文件

1.读操作
def get_json_file_content(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = json.load(f)
            return content
    except FileNotFoundError:
        print('Error: 文件不存在')
        return None
2.写操作
def write_json_file(content, file_path):
    while True:
        try:
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(content, f)
                return True
        except TypeError:
            print('文件格式错误')
            return False

3. 二进制文件

1.读操作
def get_binary_file(file_path):
    try:
        with open(file_path, 'rb') as f:
            image_data = f.read()
            return image_data
    except FileNotFoundError:
        print('路径错误')
        return None
2.写操作
def write_binary_file(old_file_path,new_file_path):
        try:
            with open(old_file_path, 'rb') as f:
                image_data = f.read()
        except FileNotFoundError:
            print('路径错误')
            return None
        with open(new_file_path, 'wb') as f:
            new_data = f.write(image_data)
        return new_data
if __name__ == '__main__':

    # a = write_text_file('123asd', './aaa.text')
    # a = get_json_file_content('./aa.json')
    # print(a)

    # a = write_json_file('123456', './aaa.json')
    # a = get_binary_file('./aaa.jpg')
    # a = write_binary_file('./aa.jpg', './aaa.png')
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,695评论 19 139
  • 关于Mongodb的全面总结 MongoDB的内部构造《MongoDB The Definitive Guide》...
    中v中阅读 32,140评论 2 89
  • 一、快捷键 ctr+b 执行ctr+/ 单行注释ctr+c ...
    o_8319阅读 11,110评论 2 16
  • 周末想家 找到熟识的同学替课 向导员拿了假条 买好了火车票就回家了 晚点的火车让我苦站了两小时 到站的时候天也冷了...
    玉彧阅读 3,698评论 1 0
  • 大一时我参加学生会新闻部,然后做部长,和一群志气相投的朋友激扬文字,度过一段难忘的日子。 在大二下的时候,成功竞选...
    大学的故事阅读 3,987评论 0 4