当前位置: 移动技术网 > IT编程>脚本编程>Python > 2020Python作业九——函数的基本应用

2020Python作业九——函数的基本应用

2020年03月18日  | 移动技术网IT编程  | 我要评论

奇瑞汽车配件,蜂享w100,道德底线大结局

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('{}\n'.format(cmd), encoding='utf-8'))
        continue  
    else:
        with open(r'access.log', 'rb') as f:
            f.write(bytes('{}\n'.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\n
        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('{}:{}\n'.format(name,pwd))
    
name=input('your name>>: ')
pwd=input('your name>>: ')
register(name,pwd)

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网