python 檔案操作,
開啟檔案的幾種模式
open('path') #預設唯讀開啟open('path','r+') #讀寫入模式開啟。如果有內容,就會從頭覆蓋相應字串的內容open('path','w')#寫入,覆蓋檔案,重新寫入。沒有檔案就自己建立open('path','w+ ')#讀寫,作用同上open('path','a')# 寫入,在檔案末尾追加內容,檔案不存在就建立open('path','a'+)#讀寫,同上。 最常用open('path','b') #開啟二進位檔案open('path','U')#支援所有的分行符號號實戰:登陸註冊
#!/usr/bin/env python#coding:utf-8f=open('user.txt','a+')#單行寫入#f.write("wd:1234")#多行寫入#names=["pc:123\n","panda:123\n"]#f.writelines(names)#互動式註冊while True: name=raw_input('請輸入使用者姓名:').strip() password=raw_input('請輸入您的密碼:').strip() repass=raw_input('請再次輸入密碼:').strip() if len(name)==0: print "使用者名稱不可為空,請重新輸入!!" continue; if len(password)==0 or password !=repass: print "密碼輸入有誤" continue; else: print "恭喜你,註冊成功" break;f.write("%s:%s" %(name,password))f.close()
#!/usr/bin/env python#coding:utf-8fo=open("user.txt")'''num=1while True: line=fo.readline()# print repr(line) print "%s-->%s" %(num,line.rstrip("\n")) num+=1 if len(line)==0: break'''#從檔案中讀取所有字元,並存為字典dict1={}content=fo.readlines() #講檔案結果儲存為列表fo.close()#print contentfor user in content: name=user.rstrip("\n").split(":")[0]# print name dict1[name]=user.rstrip("\n").split(":")[1]#print dict1#判斷使用者的帳號密碼。都ok提示登陸成功。否則失敗count=0while True: count+=1 if count >3: print "對不起,您輸入的錯誤次數過多,賬戶鎖定。請聯絡管理員" break name=raw_input('請輸入使用者姓名:').strip() if name not in dict1: print "使用者名稱不存在,請重新輸入!!" continue; password=raw_input('請輸入您的密碼:').strip() if password !=dict1[name]: print "密碼輸入有誤" continue; else: print "恭喜你,登陸成功" break;