• 3-17作业


    1、编写文件修改功能,调用函数时,传入三个参数(修改的文件路径,要修改的内容,修改后的内容)既可完成文件的修改

    import os
    def file(src_fiule, old_content, new_content):
        with open(r'{}'.format(src_fiule), 'rb') as rf,
            open(r'{}.swap'.format(src_fiule), 'wb') as wf:
            while True:
                res = rf.readline().decode('utf-8')
                if old_content in res:
                    data = res.replace('{}'.format(old_content), '{}'.format(new_content))
                    wf.write(bytes('{}'.format(data), encoding='utf-8'))
                else:
                    wf.write(bytes('{}'.format(res), encoding='utf-8'))
                if len(res) == 0:
                    break
        os.remove(r'{}'.format(src_fiule))
        os.rename('{}.swap'.format(src_fiule), '{}'.format(src_fiule))
        return '修改成功'
    
    if __name__ == '__main__':
        inp_src = input("请输入文件路径:").strip()
        old_content = input("请输入要修改的内容:").strip()
        new_content = input("请输入修改后的内容:").strip()
        if inp_src and old_content and new_content:
            msg = file(inp_src, old_content, new_content)
            print(msg)
        else:
            print("修改失败")
    import os
    
    
    # 函数定义
    def change_file(file_path, old, new):
        '''
        :param file_path: 修改的文件路径
        :param old: 要修改的内容
        :param new: 修改后的内容
        :return:
        '''
    
        # 1) 先将文件中所有的数据一行一行读取出来
        # 注意: 不要同时操作同一个文件
        # file_path: /python相关/python_files/01 python班级/python14期/作业讲解/day13/test.txt
        # 方式一: 操作系统同时打开了两个文件,同时占用操作系统两个资源
        # with open(file_path, 'r', encoding='utf-8') as f, open('copy.txt', 'w', encoding='utf-8') as w:
        #     # 如果文件比较大的时候,用for循环一行一行读取更好
        #     for line in f:
        #         line = line.replace(old, new)  # old:tank3,  new: egon
        #
        #         # list1.append(line)
        #         w.write(line)
        # 将修改后的数据copy.txt文件,改名为file_path
        # os.rename('copy.txt', file_path)
    
        # 方式二: 操作系统只开一个文件
        list1 = []
        with open(file_path, 'r', encoding='utf-8') as f:
            # 如果文件比较大的时候,用for循环一行一行读取更好
            for line in f:
                line = line.replace(old, new)  # old:tank3,  new: egon
                list1.append(line)
    
        # 执行到此处,操作系统已经回收打开文件的资源
        with open(file_path, 'w', encoding='utf-8') as f:
            for line in list1:
                f.write(line)
    
    change_file(
        'a.txt',
        'tom3',
        'jack'
    )
    优质版

    2、编写tail工具

    import time
    def tail():
    with open("log.txt","rb") as f:
    f.seek(0,2)
    while True:
    new_msg = f.readline()
    if len(new_msg)==0:
    time.sleep(1)
    else:
    print(new_msg.decode("utf-8"))
    tail()

    #另一个文件
    def write_log():
    with open("log.txt","a",encoding="utf-8") as f:
    msg = input("请输入日志内容")
    f.write(f" {msg}")
    write_log()

    3、编写登录功能

    def login(inp_u, inp_p):
        with open(r'db.txt', 'rt', encoding='utf-8') as f:
            for line in f:
                user, pwd = line.strip().split(':')
                if inp_u == user and inp_p == pwd:
                    print("登录成功")
                    break
            else:
                print("用户名密码错误")
    if __name__ == '__main__':
        inp_u = input("用户名:").strip()
        inp_p = input("密码:").strip()
        login(inp_u, inp_p)

     

    # 注意: 用于最后一题
    # user_info --> 用于记录当前用户是否登录,
    # 若已登录,则给user对应的value值替换成当前用户名
    user_info = {'user': None}
    
    
    # 函数定义
    def login():
        username = input('请输入用户名: ').strip()
        password = input('请输入密码: ').strip()
        if username == 'tank' and password == '123':
    
            user_info['user'] = username
    
            print('登录成功!')
        else:
            print('登录失败!')
    
    
    # 函数调用
    login()
    优质版

    4、编写注册功能

    def register(inp_u, inp_p):
        with open(r'db.txt', 'a+t', encoding='utf-8') as f:
                f.seek(0, 0)
                for line in f:
                    user, *_ = line.strip().split(':')
                    if inp_u == user:
                        print("用户名已存在")
                        break
                else:
                    f.write('{}:{}
    '.format(inp_u, inp_p))
    if __name__ == '__main__':
        inp_u = input("用户名:").strip()
        inp_p = input("密码:").strip()
        register(inp_u, inp_p)
    # 函数定义
    def register():
        username = input('请输入用户名: ').strip()
        password = input('请输入密码: ').strip()
        re_password = input('请输入密码: ').strip()
        if password == re_password:
            print(f'[{username}]注册成功')
    
        else:
            print('注册失败!')
    
    
    # 函数调用
    # register()
    优质版

     

    5、编写用户认证功能

    def login():
        inp_u = input("用户名:").strip()
        inp_p = input("密码:").strip()
        with open(r'db.txt', 'rt', encoding='utf-8') as f:
            for line in f:
                user, pwd = line.strip().split(':')
                if inp_u == user and inp_p == pwd:
                    print("登录成功")
                    return True
            else:
                print("用户名密码错误")
                return False
    def check_user(user_check):
        if user_check:
            print("有趣的功能")
        else:
            print("请先登录")
    def main():
        user_check = False
        msg = """
        1、登录
        2、有趣的功能
        """
        tag = True
        dic = {
            '1': True,
            '2': False
        }
        while tag:
            print(msg)
            num = input("请输入编号:").strip()
            if not num.isdigit() and num not in dic:
                print("必须输入指定编号")
            else:
                if dic[num]:
                    user_check = login()
                else:
                    check_user(user_check)
    if __name__ == '__main__':
        main()

    # 函数定义
    def check_role(username, password, role):
        if username == 'tank' and password == '123':
    
            if role == 'SVIP':
                print('超级会员,尊享所有服务~')
    
            elif role == 'VIP':
                print('普通会员,享受部分服务~')
    
            else:
                print('当前用户没有服务权限~')
    
    
    # 函数调用
    # check_role('tank', '123', 'SVIP')
    优质版

    选做题:编写ATM程序实现下述功能,数据来源于文件db.txt

    # db.txt
    '''
    tank:0
    
    '''
    
    
    # 1、充值功能:用户输入充值钱数,db.txt中该账号钱数完成修改
    # 函数定义
    def pay_money(username):
        '''
        :param username: 充值的用户
        :return:
        '''
        # {'tank': 0}  0 ---> 1000
        # 1) 将db.txt文件中所有的用户数据读取出来存放在一个字典中
        dic = {}  # 用于存放用户名与金额的字典
        with open('db.txt', 'r', encoding='utf-8') as f:
            for line in f:
                user, money = line.strip().split(':')
                dic[user] = int(money)
    
        # 校验用户是否登录
        if not user_info.get('user'):
            # 若果没有用户登录,则调用登录功能
            login()
    
        # 2) 校验当前传入的username用户是否存在
        if username not in dic:
            print('用户不存在,结束程序!')
            # 若用户不存在,则结束程序
            return
    
        # 3) 循环让用户输入充值的金额
        while True:
            money = input('请输入充值金额').strip()
            # 若用户输入的不是数字,则让用户重新输入
            if not money.isdigit():
                print('输入的必须是数字!')
                continue
    
            money = int(money)
    
            # 4) 给当前用户的金额加钱
            dic[username] += money
    
            # 5) 将修改后的用户数据重新写入文件中
            with open('db.txt', 'w', encoding='utf-8') as f:
                for user, money in dic.items():
                    f.write(f'{user}:{money}
    ')
            break
    
    
    # 函数调用
    # pay_money('tank')
    
    
    # 2、转账功能:用户A向用户B转账1000元,db2.txt中完成用户A账号减钱,用户B账号加钱
    '''db2.txt
    tank:2000
    egon:1001
    
    '''
    
    
    # 函数定义
    def transfer(A_user, B_user, transfer_money):
        '''
    
        :param A_user: 转账用户
        :param B_user: 收款用户
        :param money: 转账金额
        :return:
        '''
        dic = {}
        with open('db2.txt', 'r', encoding='utf-8') as f:
            for line in f:
                user, money = line.strip().split(':')
                dic[user] = int(money)
    
        # 校验用户是否登录
        if not user_info.get('user'):
            # 若果没有用户登录,则调用登录功能
            login()
    
        # 作业: 判断转账用户与收款用户是否存在
        if A_user not in dic:
            print('转账用户不存在')
            return
    
        if B_user not in dic:
            print('收款用户不存在')
            return
    
        print('转账前: ', dic)
        # 1) 判断转账用户的金额是否 大于 等于 转账金额
        if dic.get(A_user) >= transfer_money:
    
            # 2)转账用户扣钱
            dic[A_user] -= transfer_money
    
            # 3)收款用户加钱
            dic[B_user] += transfer_money
    
            print('转账后: ', dic)
    
            # 4) 此时转账与收款用户的数据都已经修改过了,重新写入文件中
            with open('db2.txt', 'w', encoding='utf-8') as f:
                for user, money in dic.items():
                    f.write(f'{user}:{money}
    ')
    
    
    # 函数调用
    # transfer('egon', 'tank', 1000)
    
    
    # 3、提现功能:用户输入提现金额,db.txt中该账号钱数减少
    '''db3.txt
    tank:2000
    egon:1001
    
    '''
    
    
    # 函数定义
    def withdraw(username, get_money):
        '''
        :param user: 提现用户
        :param money: 提现金额
        :return:
        '''
        # 1)获取所有用户的数据
        dic = {}
        with open('db3.txt', 'r', encoding='utf-8') as f:
            for line in f:
                user, money = line.strip().split(':')
                dic[user] = int(money)
    
        # 校验用户是否登录
        if not user_info.get('user'):
            # 若果没有用户登录,则调用登录功能
            login()
    
        # 2) 判断当前用户是否存在
        if username not in dic:
            return
    
        if dic.get(username) >= get_money:
            # 提现用户扣钱
            dic[username] -= get_money
    
            print(dic)
            with open('db3.txt', 'w', encoding='utf-8') as f:
                for user, money in dic.items():
                    f.write(f'{user}:{money}
    ')
    
    
    # 函数调用
    # withdraw('egon', 1)
    
    
    # 4、查询余额功能:输入账号查询余额
    def check_money(username):
        dic = {}
        with open('db3.txt', 'r', encoding='utf-8') as f:
            for line in f:
                user, money = line.strip().split(':')
                dic[user] = int(money)
    
        # 校验用户是否登录
        if not user_info.get('user'):
            # 若果没有用户登录,则调用登录功能
            login()
    
        # 2) 判断当前用户是否存在
        if username not in dic:
            return
    
        # 3) 返回当前用户的金额
        return dic.get(username)
    
    # 调用函数
    # money = check_money('tank')
    # print(money)
    
    
    # 选做题中的选做题:登录功能
    # 用户登录成功后,内存中记录下该状态,上述功能以当前登录状态为准,必须先登录才能操作
    代码
     
  • 相关阅读:
    JS 缓动动画封装函数
    JS 实现商品图片放大镜(大图)效果
    JS 实现春节倒计时效果
    HMTL+CSS 实现图片旋转木马效果
    HTML 解决video标签播放视频看不见&能听到声音看不到画面等问题
    GoLang Json数据的的序列化与反序列化
    GoLang 解决VsCode中提示错误 go: cannot find main module, but found .git/config in D:XXXsrcXXX to create a module there, run: cd .. && go mod init
    Flutter 容器(3)
    Flutter 容器 (2)
    Flutter 容器 (1)
  • 原文地址:https://www.cnblogs.com/2722127842qq-123/p/12512719.html
Copyright © 2020-2023  润新知