作业:
# 1、编写文件修改功能,调用函数时,传入三个参数(修改的文件路径,要修改的内容,修改后的内容)既可完成文件的修改
ANSR:
# 方式一:
def file_change():
src_file_abs_path = input("Please input src_file_abs_path: ").strip()
src_data = input("Please input src_data: ").strip()
dst_data = input("Please input dst_data: ").strip()
with open(r"{}".format(src_file_abs_path),mode="rt",encoding="utf-8") as read_f:
data = read_f.read()
with open(r"{}".format(src_file_abs_path),mode="wt",encoding="utf-8") as write_f:
write_f.write(data.replace(src_data,dst_data))
# 方式二:
def file_change():
import os
src_file_abs_path = input("Please input src_file_abs_path: ").strip()
src_data = input("Please input src_data: ").strip()
dst_data = input("Please input dst_data: ").strip()
with open(r"{}".format(src_file_abs_path), mode="rt", encoding="utf-8") as read_f,
open(r"{}.swap".format(src_file_abs_path), mode="wt", encoding="utf-8") as write_f:
for line in read_f:
data = line.replace(src_data, dst_data)
write_f.write(data)
os.remove(r"{}".format(src_file_abs_path))
os.rename(r"{}.swap".format(src_file_abs_path), r"{}".format(src_file_abs_path))
# 2、编写tail工具
ANSR:
def tail(src_file_abs_path):
import time
with open(r"{}".format(src_file_abs_path), mode="rb") as f:
f.seek(0,2)
while True:
line = f.readline()
if len(line) == 0:
time.sleep(0.1)
else:
print(line.decode("utf-8"),end="")
# 3、编写登录功能
ANSR:
def login():
inp_name = input("Please input your user name: ").strip()
inp_pwd = input("Please input your user password: ").strip()
with open("taskdb.txt",mode="rt",encoding="utf-8") as read_f:
for line in read_f:
name, pwd, *_=line.strip("
").split(":")
if name == inp_name and inp_pwd == pwd:
print("login successful")
break
else:
print("Username or password error")
# 4、编写注册功能
ANSR:
def register():
inp_name = input("Please input your user name: ").strip()
inp_pwd = input("Please input your user password: ").strip()
with open("taskdb.txt",mode="rt",encoding="utf-8") as read_f:
for line in read_f:
name, pwd, *_=line.strip("
").split(":")
if name == inp_name:
print("Username exists")
break
else:
with open("taskdb.txt", mode="at", encoding="utf-8") as write_f:
write_f.write("{}:{}:0
".format(inp_name,inp_pwd))
print("register successful")
# 5、编写用户认证功能
ANSR:
user_list=[]
def auth():
inp_name = input("Please input your user name: ").strip()
if inp_name not in user_list:
inp_pwd = input("Please input your user password: ").strip()
with open("taskdb.txt", mode="rt", encoding="utf-8") as read_f:
for line in read_f:
name, pwd, *_ = line.strip("
").split(":")
if name == inp_name and inp_pwd == pwd:
print("login successful")
break
else:
print("Username or password error")
else:
pass
# 选做题:编写ATM程序实现下述功能,数据来源于文件db.txt
# 1、充值功能:用户输入充值钱数,db.txt中该账号钱数完成修改
# 2、转账功能:用户A向用户B转账1000元,db.txt中完成用户A账号减钱,用户B账号加钱
# 3、提现功能:用户输入提现金额,db.txt中该账号钱数减少
# 4、查询余额功能:输入账号查询余额
ANSR:
/
# 选做题中的选做题:登录功能
# 用户登录成功后,内存中记录下该状态,上述功能以当前登录状态为准,必须先登录才能操作
ANSR:
/