一、提前知识点
在python中是同样和其他语言一样可以进行文件的读取写入操作,值得注意的是,Python中打开文件读取的方式有几种,分别是以下几种:
f = open('username.txt')
first_line = f.readline()
print('first line:',first_line )
f.close()
try:
f = open('username.txt')
print(f.read() )
finally:
if f:
f.close()
上面两种各有区别,第一种在打开文件进行读取之后,需要针对文件进行关闭,这是值得注意的一点,如果没有进行关闭,可能在下次进行写入过程或者出现其他莫名的错误,后者则是使用了try指令,这个可以自动在结束后进行文件关闭,但相对的来说比较繁琐,那么就有第三种比较简便的方式,with指令。
with open('username.txt') as f:
print(f.read())
二、如何进行用户交互和读取写入文件直接进行操作
这边需要用到的是我之前在Python自学之路中用到的用户交互的用法,这边针对输入对文件的内容进行比较,这边就用到了读取文件的指令。按照之前把文件的内容取出来放入变量中,这边值得注意的是我们需要强制的进行数据类型的转换(不转换不会出错,但会使得我们比较的时候结果不是我们需要的结果,就是因为实际看到的数字或者字符类型和我们需要的类型不一致导致。)
用代码来说的话就这样
username = str(input("username:"))
password = str(input("password:"))
with open('locked.txt') as f3:
account_locked = f3.readlines()
if username in account_locked :
print("your account are locked ")
readlines是读取该文件的内容,和readline是有区别的,一个简单方法就是把内容打印出来看就很清楚发现一个是读取全部,另一个是读取首行。这边也应用了if语句进行判断。
补充之前Python自学之路中,第一个习题的个人理解:
# Author: JC #打开文件
'''f = open('username.txt')
first_line = f.readline()
print('first line:',first_line )
f.close()'''
'''try:
f = open('username.txt')
print(f.read() )
finally:
if f:
f.close()
with open('username.txt') as f:
print(f.read())
'''
login_flag = 0
print("Do you want to do ?(login/apple)")
if input() == 'login'and login_flag == 0:
login_flag = 1 if login_flag == 1:
count = 1
while count < 4:
print("please enter your username and password.")
username = str(input("username:"))
password = str(input("password:"))
with open('locked.txt') as f3:
account_locked = f3.readlines()
if username in account_locked :
print("your account are locked ")
break
with open ('username.txt') as f1,open ('password.txt') as f2:
_username =f1.readlines()
_password = f2.readlines()
if username not in _username or password not in _password:
print("eorr username or password!\n you have {count} times.".format(count= 3-count))
count += 1
if count ==4:
with open('locked.txt', 'a+') as f3:
f3.write(username)
f3.write('\n')
print("your account are locked ")
else:
print("Welcome {name} to login....".format(name=username) )
break
else:
print("please enter your new account and password.")
username = input("username:")
password = input("password:")
with open('username.txt','a+') as f1:
f1.write(username) #把变量写入文件
f1.write('\n') #添加换行符
with open('password.txt','a+') as f2:
f2.write(password)
f2.write('\n')
#flag = 1