文件练习题1,2

1.把内容变成可迭代,然后遍历,发现有旧字符则替换,然后用一个n作计数器,写入新的文件,但是用os模块替换不了

file_name = input('file_name:>>>')
old_str = input('old_str:>>>')
new_str = input('new_str:>>>')
n = 0
import os
f = file_name
f_new_name = "%s.new" % f
f = open(f, 'r', encoding='UTF-8')
f_new= open (f_new_name, 'w', encoding='UTF-8')

for i in f:
if 'a' in i:
i = i.replace(old_str, new_str)
n += 1
f_new.write(i)
f.close()
f_new.close()
print(n)


os.rename(f_new_name, f)#新文件是.new格式,rename不了,怎么把.new变成txt格式?

2.实现了锁定用户的功能,但是没实现用户名和密码一一对应登陆,应该用字典保存用户名和密码信息,然后用户名指向对应的密码值进行判断登陆

user_det = input('user_det:>>>')
n = 1
lis = []
lock1 = open('D:lock_list.txt', 'r', encoding='UTF-8')
#lock1_r = lock1.read() 如果read()和readlines()同时出现,readlines则会为空
data = lock1.readlines()
lock1.close()
print(data)
for i in data:
lis.append(i.strip()) #把锁定的用户用列表形式表示出来
print(lis)
if not user_det in lis:#空列表方式判断是否为锁定的用户,应该有更好的方法
u = open('D:user_list.txt', 'r', encoding='UTF-8')
u_r =u.readlines()
p = open('D:password_list.txt', 'r', encoding='UTF-8')
p_r =p.readlines()
while n < 4:
user = input('user:>>>')
password = input('password:>>>')
if user in u_r and password in p_r: #不支持用户名和密码一一对应
print('success')
break
else:
print('%d time wrong'% n)
n += 1
if n == 4:
lock = open('D:lock_list.txt', 'a', encoding='UTF-8')
lock.write('\n'+user)
lock.close()#锁定用户
# u.close()
# p.close()
else:
print('user locked')





posted @ 2018-09-10 20:14  Freedom_L  阅读(122)  评论(0编辑  收藏  举报