# !/use/bin/env python
# -*-conding:utf-8-*-
# author:shanshan
import os
"""
1,写函数,计算传入数字参数的和。(动态传参)
"""
def sum_values(*args):  # *args是一个列表
    sum_values = sum(args)
    return sum_values
# print(sum_values(1,2,5,7,-10))
def try_open_file(alter_file_fun):  # 执行函数异常的装饰器
    def try_open(file_name, old_content, new_content):
        try:
            alter_file_fun(file_name, old_content, new_content)
        except Exception as e:
            print('替换 出错了:{}'.format(e.args))
    return try_open
"""
2,写函数,用户传入修改的文件名,与要修改的内容,执行函数,完成整个文件的批量修改操作
"""
def alter_file_1(file_name, old_content, new_content):
    """
    替换文件中旧的内容,全局修改为新的内容(但是生成了新的文件)
    :param file_name: 文件名 (同一目录下的)
    :param old_content: 旧的内容
    :param new_content: 新的内容
    :return: 无
    """
    file_path = os.path.abspath(file_name)  # 传入文件名的绝对路径
    with open(file=file_path + '副本', mode='a', encoding='utf-8') as fw:  # 写入一个文件叫副本,用追加的方式
        with open(file_path, 'r', encoding='utf-8')as fr:  # 找到传入的文件
            while True:
                str_line_file = fr.readline()
                if str_line_file:  # 如果可以读到一行的内容继续--->
                    if old_content in str_line_file:  # 判断老的内容是否在这一行中
                        replace_line = str_line_file.replace(old_content, new_content)  # 如果存在则将老内容全部替换
                        fw.write(replace_line)  # 写入新的内容
                    else:
                        fw.write(str_line_file)  # 否则的话写入 老的内容
                else:
                    break  # 如果这一行读不到了就退出程序
    os.remove(file_path)  # 删除旧文件
    os.renames(file_path + '副本', file_path)  # 将新文件修改为 旧文件的名称
# alter_file_1('english_text','dayto','Today')
@try_open_file
def alter_file_2(file_name, old_content, new_content):
    """
    替换文件中旧的内容,全局修改为新的内容(源文件的基础上)
    :param file_name: 文件名 (同一目录下的)
    :param old_content: 旧的内容
    :param new_content: 新的内容
    :return: 无
    """
    file_path = os.path.abspath(file_name)  # 传入文件名的绝对路径
    with open(file_path, 'r', encoding='utf-8')as f:  # 以读的方式打开将内容保存在一个变量中(也就是宝存到了内存)
        str_file = f.read()
    with open(file_path, 'w', encoding='utf-8')as f:
        str_replace_file = str_file.replace(old_content, new_content)  # 以写的方式重新打开写入新的内容
        f.write(str_replace_file)
# alter_file_2('1111','dayto','Today')
"""
3,写函数,检查用户传入的对象(字符串、列表、元组)的每一个元素是否含有空内容。
"""
def check_input(str_list_tuple):
    flag = False
    for i in str_list_tuple:
        if (' ' or '') in i:  # 循环遍历每个值,如果有空的内容那就将flag设置为true,代表有空的内容
            flag = True
    if flag == False:  # 没有在里面那么flag的值还是false
        print('{}:中无空内容'.format(str_list_tuple))
    else:
        print('{}:中有空内容'.format(str_list_tuple))
# check_input(['1','2   ','    '])
"""
4,写函数,检查传入字典的每一个value