第三周day02作业

import time
import os

# 1、编写文件修改功能,调用函数时,传入三个参数(修改的文件路径,要修改的内容,修改后的内容)既可完成文件的修改
# 方式一:一次性读完修改完再覆盖原文件
# def file_modify(path,old,new):
# '''文件修改'''
# with open(r'{}'.format(path),'r',encoding='utf-8') as f:
# res = f.read()
# data = res.replace(old,new)
# with open(r'{}'.format(path),'w',encoding='utf-8') as f1:
# f1.write(data)
# file_modify(r'test.txt','alex','dsb')
# 方式二:以读的方式打开原文件,以写的方式打开一个临时文件,一行行读取原文件内容,修改完后写入临时文件,删掉原文件,将临时文件重命名原文件名
def file_modify(path,old,new):
'''文件修改'''
with open(r'{}'.format(path),'r',encoding='utf-8') as f,\
open(r'.{}.swap'.format(path),'w',encoding='utf-8') as f1:
for line in f:
f1.write(line.replace(old,new))
os.remove(r'{}'.format(path))
os.rename(r'.{}.swap'.format(path),r'{}'.format(path))

# file_modify(r'test.txt','alex','dsb')



# 2、编写tail工具
# 需要新建一个py文件执行文件追加内容的操作
# 该文件打开的路径应该与输入的路径一致
# with open('test.txt','a',encoding='utf-8') as f:
# f.write('哈哈哈\n')
def tail_tool():
'''tail工具'''
file_path = input('请输入要监听的文件路径:')
with open('{}'.format(file_path),'rb') as f:
f.seek(0,2)
while True:
line = f.readline()
if line:
print(line.decode('utf-8'),end='')
else:
time.sleep(0.5)
# tail_tool()
# 3、编写登录功能
# 需提前创建好user_info.txt
def login():
'''登录功能'''
print('欢迎来到登录界面'.center(30, '*'))
user = input('请输入用户名:')
with open(r'user_info.txt','r',encoding='utf-8') as f:
if not f.read():
print('用户文件中现在没有任何用户存在,请先注册')
else:
f.seek(0,0)
for line in f:
username,password = line.strip().split(':')
if user in username:
pwd = input('请输入密码:')
if pwd == password:
print('登录成功')
break
else:
print('密码错误')
else:
print('该用户不存在')
# login()

# 4、编写注册功能
# 需提前创建好user_info.txt
def register():
'''注册功能'''
print('欢迎来到注册界面'.center(30, '*'))
user = input('请输入用户名:')
pwd = input('请输入密码')
with open(r'user_info.txt','r+',encoding='utf-8') as f1:
if not f1.read():
f1.write('{}:{}\n'.format(user,pwd))
print('注册成功')
else:
f1.seek(0,0)
for line in f1:
username,password = line.strip().split(':')
if user in username:
print('该用户名存在,请重新注册')
break
else:
f1.write('{}:{}\n'.format(user,pwd))
print('注册成功')
# register()

猜你喜欢

转载自www.cnblogs.com/h1227/p/12511131.html