day11-作业(封包)

import json


def txtfile_read(filename):
    while True:
        try:
            with open(filename,'r',encoding='utf-8') as txtfile:
                content = txtfile.read()
                print('读取成功')
            return content #,成功返回文本实, 读取文本文件
            break
        except FileNotFoundError: #发生文件不存在的处理方案
            order = input('文件未找到,是否创建?y/n:')
            if order == 'y':
                f = open(filename,'w',encoding='utf-8')
                f.close()
                order1 = input('是否写入内容?y/n:')
                if order1 == 'y':
                    new = input('输入写入内容:')
                    with open(filename,'w',encoding='utf-8') as txtfile:
                        txtfile.write(new)
                        print('写入成功!')
            else:
                filename = input('请重新输入路径:')


def txtfile_write(filename,title): # 文件写入
    order = input('请选择写入方式(1.覆写,2.追加):')
    if order == '1':
        with open(filename,'w',encoding='utf-8') as txtfile:
            txtfile.write(title)
            print('写入成功')
    elif order == '2':
        with open(filename,'a',encoding='utf-8') as txtfile:
            txtfile.write(title)
            print('写入成功')


def jsonfile_read(filename): # json的读取,这个其实也可以和上面重新创建,有兴趣的同学可以试试
    try:
        with open(filename,'r',encoding='utf-8') as jsonfile:
            context = json.load(jsonfile)
            print('读取成功')
            return  context
    except FileNotFoundError:
            print('文件没找到,暂时不支持重新创建')


def jsonfile_write(filename,title = ''): # json写入
    with open(filename, 'w', encoding='utf-8') as jsonfile:
        json.dump(title, jsonfile)
        print('写入成功')

你可能感兴趣的:(day11-作业(封包))