1、编写文件修改功能,调用函数时,传入三个参数(修改的文件路径,要修改的内容,修改后的内容)即可完成文件的修改
def modify(file_path,old,new):
import os
with open(r'{}'.format(file_path),'rt',encoding='utf-8') as f1,
open('.a.txt.swap','wt',encoding='utf-8') as f2:
for line in f1:
line = line.replace(old,new)
f2.write(line)
os.remove(r'{}'.format(file_path))
os.rename('.a.txt.swap',r'{}'.format(file_path))
def main():
file_path = input('请输入你需要修改的文件路径:').strip()
old = input('请输入需要修改的内容:').strip()
new = input('请输入修改后的内容:').strip()
modify(file_path,old,new)
main()
2、编写tail工具
import time
def tail():
file_path = input('请输入你需要监测的文件路径:').strip()
with open(r'{}'.format(file_path),'rb') as f:
f.seek(0,2)
while True:
content = f.readline()
if len(content) == 0:
time.sleep(0.5)
print(content.decode('utf-8'),end='')
tail()
3、编写登录功能
def log_in():
flag = True
while flag:
inp_name = input('请输入你的账号:').strip()
with open(r'db.txt','rt',encoding='utf-8') as f:
for user_info in f:
user_name,pwd = user_info.strip().split(':')
if inp_name == user_name:
inp_pwd = input('请输入你的密码:').strip()
if inp_pwd == pwd:
print('登录成功。')
flag = False
break
else:
print('密码错误,登录失败。')
break
else:
print('你输入的账号不存在,请重新输入。')
4、编写注册功能
def register():
while True:
inp_name = input('请输入你要注册的账号:').strip()
with open(r'db.txt','r+t',encoding='utf-8') as f:
for user_info in f:
user_name,*_ = user_info.strip().split(':')
if inp_name == user_name:
print('你输入的账号已存在,请重新输入。')
break
else:
while True:
inp_pwd = input('请为你的账号设置一个密码:').strip()
inp_pwd1 = input('请确认刚才输入的密码:').strip()
if inp_pwd == inp_pwd1:
f.seek(0,2)
f.write('{}:{}
'.format(inp_name,inp_pwd))
print('恭喜,注册成功。')
break
print('两次输入的密码不一致,请重新设置密码。')
break