python 檔案操作,

來源:互聯網
上載者:User

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;

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.