python学习13——课后练习

# 1、编写文件修改功能,调用函数时,传入三个参数(修改的文件路径,要修改的内容,修改后的内容)既可完成文件的修改
import os
def edit_file(file_path,old_c,new_c):
with open(r'{}'.format(file_path),mode='rb') as f1,\
open(r'{}.swap'.format(file_path),mode='wb')as f2:
while True:
cont= f1.readline().decode('utf-8')
if old_c in cont:
newcont =cont.replace(old_c,new_c)
f2.write(newcont.encode('utf-8'))
else:
f2.write(cont.encode('utf-8'))
if len(cont) == 0:
break
os.remove(file_path)
os.rename('{}.swap'.format(file_path),'{}'.format(file_path))
file_path = input('输入文件路径').strip()
old_c = input('输入要修改的内容')
new_c = input('修改后的内容')
edit_file(file_path,old_c,new_c)
'''
输入文件路径edit.txt
输入要修改的内容好
修改后的内容坏

Process finished with exit code 0
'''
# 2、编写tail工具
import time
def tail(logpath):
with open(logpath,mode='rb')as tail_f:
tail_f.seek(0,2)
while True:
line = tail_f.readline()
if line :
print(line.decode('utf-8'))
else:
time.sleep(0.1)
logpath = input('输入监听文件的路径')
tail(logpath)
'''
输入监听文件的路径access.log
12312

sdgfhj

azxcxzh

asdh

'''
# 3、编写登录功能
def login(name,password):
with open('info.txt','rt',encoding='utf-8') as login_f:
for line in login_f:
username,userpsd =line.strip().split(':')
if name not in username :
print('用户不存在')
break
elif name== username and password ==userpsd:
print('登陆成功')
break
else:
print('登录失败')
break
name = input('输入用户名')
password = input('输入密码')
login(name,password)
# 4、编写注册功能
def reg(name,password):
with open('reg.txt','rt',encoding='utf-8')as f1,\
open('reg.txt','at',encoding='utf-8')as f2:
for line in f1:
username,userpsd=line.strip().split(':')
if name in username:
print('用户名已存在')
else:
f2.write('{}:{}'.format(name,password))
name = input('输入用户名')
password = input('输入密码')
reg(name,password)

猜你喜欢

转载自www.cnblogs.com/heirenxilou/p/12512797.html