zoukankan      html  css  js  c++  java
  • 2020Python练习九——函数的基本应用

    2020Python练习九——函数的基本应用

    @2020.3.17

    利用函数,改写功能

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

    import os
    def file(file_path, old_content, new_content):
        with open(r'{}'.format(file_path),mode='rb') as read_f,
                open(r'{}.swap'.format(file_path,mode='wb')) as write_f:
             #.swap 是Linux系统的命名规则,‘.’开头是隐藏文件
            while True:
                res = read_f.readline().decode('utf-8')
                if old_content in res:
                    res2 = res.replace('{}'.format(old_content),'{}'.format(new_content))
                    write_f.write(bytes('{}'.format(res2),encoding='utf-8'))
                else:
                    write_f.write(bytes('{}'.format(res),encoding='utf-8'))
                break
        os.remove('{}'.format(file_path))  # 删除原文件
        os.rename('{}.swap'.format(file_path),'{}'.format(file_path)) #将新文件重命名为原文件名
    
    file_path = input('please input file path:')
    old_content = input('please input content that needs to rewrite:')
    new_content = input('please input new content:')
    if file_path and old_content and new_content:
        mesg = file(file_path, old_content, new_content)
        print(mesg)
    else:
        print('修改失败,请重试')

    # 2、编写tail工具

    def tail():
        cmd = input('请输入命令:').strip()
        if cmd == 'tail -f access.log':
            with open(r'access.log', 'a+b') as f:
                f.write(bytes('{}
    '.format(cmd), encoding='utf-8'))
            continue  
        else:
            with open(r'access.log', 'rb') as f:
                f.write(bytes('{}
    '.format(cmd), encoding='utf-8'))
    tail()

    # 3、编写登录功能

    def login(inp_username,inp_password):
    with open('user.txt',mode='rt',encoding='utf-8') as f:
        for line in f:     # 验证,把用户输入的名字和密码与读出的内容作对比
            print(line,end='') # egon:123
    
            username,password=line.strip().split(':')
            if inp_username == username and inp_password == password:
                print('login successfull')
                break
        else:
            print('账号或密码错误')
    
    inp_username=input('your name>>: ').strip()
    inp_password=input('your password>>: ').strip()
    login(inp_username,inp_password)

    # 4、编写注册功能

    def register(name,pwd):
    with open('register.txt',mode='at',encoding='utf-8') as f:
        f.write('{}:{}
    '.format(name,pwd))
        
    name=input('your name>>: ')
    pwd=input('your name>>: ')
    register(name,pwd)
  • 相关阅读:
    hdu5360 Hiking(水题)
    hdu5348 MZL's endless loop(欧拉回路)
    hdu5351 MZL's Border(规律题,java)
    hdu5347 MZL's chemistry(打表)
    hdu5344 MZL's xor(水题)
    hdu5338 ZZX and Permutations(贪心、线段树)
    hdu 5325 Crazy Bobo (树形dp)
    hdu5323 Solve this interesting problem(爆搜)
    hdu5322 Hope(dp)
    Lightoj1009 Back to Underworld(带权并查集)
  • 原文地址:https://www.cnblogs.com/bigorangecc/p/12511136.html
Copyright © 2011-2022 走看看