Python生活不易 我用pythonPython自学与资料分享

Module Management file Operation

2018-07-26  本文已影响293人  GHope

通过在不同的模块中定义对不同类型文件操作的函数,后在管理模块进行导入并使用,进一步熟悉模块化管理及文件相关操作。


目录结构

函数导入及调用

from homework.txtManagement import read_txt
from homework.txtManagement import write_txt
from homework.binManagement import read_bin
from homework.binManagement import write_bin
import homework.jsonManagement


if __name__ == '__main__':
    content1 = read_txt('./poems.txt')
    print(content1)
    write_txt('./poems.txt','李白')
    content2 = read_bin('./hacker.jpg')
    print(content2)
    write_bin('./hacker.jpg', content2)
    content3 = homework.jsonManagement.read_json('./test.json')
    print(content3)
    homework.jsonManagement.write_json('./test.json',content3)


运行结果:
花间一壶酒,独酌无相亲。
举杯邀明月,对影成三人。
b''
{'序号': [1, 2, 3]}

注:我觉得应该没什么问题,可是二进制那个输出让我有点迷

对文本文件操作的封装

def read_txt(txt_local):
    with open(txt_local, 'r', encoding='utf-8') as rft:
        content =rft.read()
        return content


def write_txt(txt_local, write_value):
    with open(txt_local, 'w', encoding='utf-8') as wft:
        wft.write(write_value)


if __name__ == '__main__':
    pass




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:文件不存在!!!')


def write_text_file(content, file_path):
    """
    将数据写到指定的文本文件中
    :param content: 写入的内容
    :param file_path: 文件路径
    :return: 状态提示
    """
    try:
        with open(file_path, 'w', encoding='utf-8')as f:
            f.write(content)
            f.write()
            return True
    except TypeError:
        print("Error:内容必须是字符串!!!")
        return False


if __name__ == '__main__':
    get_text_file_content('./aa.txt')
    write_text_file('True', './aa.txt')

对二进制文件操作的封装

def read_bin(bin_local):
    with open(bin_local, 'rb') as rbt:
        content = rbt.read()
        return content


def write_bin(bin_local, write_value):
    with open(bin_local, 'wb') as wbt:
        wbt.write(write_value)


if __name__ == '__main__':
    pass

对json文件操作的封装

import json


def read_json(json_local):
    with open(json_local, 'r', encoding='utf-8') as rfj:
        content = json.load(rfj)
        return content


def write_json(json_local, write_value):
    with open(json_local, 'w', encoding='utf-8') as wft:
        json.dump(write_value, wft)


if __name__ == '__main__':
    pass
上一篇 下一篇

猜你喜欢

热点阅读