作业9
编写文件修改功能,调用函数时,传入三个参数(修改的文件路径,要修改的内容,修改后的内容)
import os
def alter(file,old_str,new_str):
with open(file, "r", encoding="utf-8") as f1, open("{}.swap".format(file), "w", encoding="utf-8") as f2:
for line in f1:
if old_str in line:
line = line.replace(old_str, new_str)
f2.write(line)
os.remove(file)
os.rename("{}.swap".format(file), file)
alter('file1','zc','牛逼')
既可完成文件的修改编写tail工具
import time
def tail(file):
with open(file, 'rt', encoding='utf-8') as f:
f.seek(0, 2)
while True:
res = f.readline()
if not res:
time.sleep(0.5)
print(res)
编写登录功能
编写注册功能
编写用户认证功能
def login(username, password):
"""
登录
"""
with open('a.txt', 'r', encoding="utf-8") as f:
for line in f: # 一行一行的读取
line = line.strip()
line_list = line.split(":")
if username == line_list[0] and password == line_list[1]:
return True
return False
def register(username, password):
"""
注册
"""
with open('a.txt', "a", encoding="utf-8") as f:
f.write('{}:{}\n'.format(username,password))
return True
def user_exist(username):
'''
验证用户注册是否存在
'''
with open('a.txt', "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
line_list = line.split(":")
if username == line_list[0]:
return True
return False
def main():
while True:
msg = """
0 退出
1 登录
2 注册
"""
print(msg)
cmd = input('请输入命令编号>>: ').strip()
if not cmd.isdigit():
print('必须输入命令编号的数字,傻叉')
continue
# 判断当前用户如果不在dic字典中,执行
if cmd not in dic:
print('输入的命令不存在')
continue
print(dic.get(cmd))
if cmd=='1':
user=input('请输入你的账号:').strip()
pwd=input('请输入你的密码:').strip()
is_login=login(user,pwd)
if is_login:
print('登录成功')
else:print('登录失败')
elif cmd=='2':
user = input('请输入你的注册账号:').strip()
pwd = input('请输入你的注册密码:').strip()
is_exist=user_exist(user)
if is_exist:
print('用户已注册')
else:
result = register(user, pwd)
if result:
print("注册成功")
else:
print("注册失败")
main()

浙公网安备 33010602011771号