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