python-code-05

來源:互聯網
上載者:User

標籤:重複   ffd   mode   word   使用者名稱   檔案讀取   讀取   編寫程式   一個   

今日作業:
一、實現使用者註冊功能
思路:
使用者輸入使用者名稱、密碼
將使用者輸入的內容按照固定的格式,比如:egon:123,存入檔案
可以往一個檔案中重複註冊新的使用者名稱和密碼
while True:    name_inp = input(‘name>>: ‘).strip() #要驗證使用者名稱得事先建立這個檔案    pwd_inp = input(‘password>>: ‘)    chk_pwd_inp = input(‘password>>: ‘)    if pwd_inp == chk_pwd_inp:        with open(‘db_file‘,mode=‘at‘,encoding=‘utf-8‘) as f:            f.write(‘%s:%s\n‘ %(name_inp,pwd_inp))    else:        print(‘兩次密碼不一致‘)
View Code

二、實現使用者驗證功能更:
思路:
使用者輸入帳號密碼,從檔案中讀出帳號密碼,與使用者輸入的進行比對
name_inp = input(‘username>>: ‘).strip()pwd_inp = input(‘password>>: ‘)with open(‘db_file‘,mode=‘rt‘,encoding=‘utf-8‘) as f:    for line in f:        line = line.strip(‘\n‘)        line = line.split(‘:‘)        name = line[0]        pwd = line[1]        if name_inp == name and pwd_inp == pwd:            print(‘驗證成功‘)            break    else:        print(‘使用者名稱或密碼錯誤‘)
View Code

三、編寫程式,實現檔案拷貝功能
思路:
使用者輸入源檔案路徑和目標檔案路徑,執行檔案拷貝

import sysif len(sys.argv) != 3:    print(‘usage: cp source_file target_file‘)    sys.exit()source_file,target_file=sys.argv[1],sys.argv[2]with open(source_file,‘rb‘) as read_f,open(target_file,‘wb‘) as write_f:    for line in read_f:        write_f.write(line)
View Code


明早默寫:
迴圈讀取檔案
f=open(‘db_file‘,‘rt‘,encoding=‘utf-8‘)for line in f:    print(line)f.close()with open(‘db_file‘,mode=‘rt‘,encoding=‘utf-8‘) as f:    for line in f:        print(line,end=‘‘)
View Code

唯讀方式讀取檔案,並說明注意事項
with open(‘db_file‘,mode=‘rt‘,encoding=‘utf-8‘) as f:    print(f.read())1、只能讀,不能寫2、在檔案不存在時,會報錯,在檔案存在的時候會將檔案指標移動到檔案的開頭,讀完就在末尾了
View Code

唯寫的方式寫檔案,並說明注意事項
with open(‘w‘,mode=‘wt‘,encoding=‘utf-8‘) as f:    f.write(‘w‘)1、只能寫,不能讀2、在檔案不存在時會建立空檔案,在檔案存在的時候會將檔案內容清空
View Code

只追加寫的方式寫檔案,並說明注意事項
with open(‘w‘,mode=‘at‘,encoding=‘utf-8‘) as f:    f.write(‘\nr‘)1、只能寫,不能讀2、在檔案不存在時會建立空檔案,在檔案存在的時候會將指標移動到檔案末尾
View Code

簡述t與b模式的區別
t模式:只有文字檔才能用t模式,也只有文字檔才有字元編碼的概念b模式:一定不能指定字元編碼,只有t模式才與字元編碼有關b是二進位模式,是一種通用的檔案讀模數式,因為所有的檔案在硬碟中都是以二進位形式存放的
View Code

python-code-05

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.