# 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("修改失败")
# 2、编写tail工具
import time
import os
def test():
with open(r'access.log', 'ab') as wf:
wf.write('2020114455001 egon转账200w\n'.encode('utf-8'))
def tail():
if not os.path.exists(r'access.log'):
with open(r'access.log', 'wt', encoding='utf-8') as f:
f.write('file is created\n')
with open(r'access.log', 'rb') as rf:
rf.seek(0, 2)
while True:
line = rf.readline().decode('utf-8')
test()
print(line, end='')
time.sleep(1)
tail()
# 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)
# 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('{}:{}\n'.format(inp_u, inp_p))
if __name__ == '__main__':
inp_u = input("用户名:").strip()
inp_p = input("密码:").strip()
register(inp_u, inp_p)
# 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()
# 选做题:编写ATM程序实现下述功能,数据来源于文件db.txt
# 1、充值功能:用户输入充值钱数,db.txt中该账号钱数完成修改
# 2、转账功能:用户A向用户B转账1000元,db.txt中完成用户A账号减钱,用户B账号加钱
# 3、提现功能:用户输入提现金额,db.txt中该账号钱数减少
# 4、查询余额功能:输入账号查询余额
# 选做题中的选做题:登录功能
# 用户登录成功后,内存中记录下该状态,上述功能以当前登录状态为准,必须先登录才能操作
来源:https://www.cnblogs.com/python--wang/p/12512715.html