一、檔案操作
1. 隻讀
1) r
以str形式
f = open('d:\檔案操作.txt',mode='r',encoding='utf-8') # r是預設的
content=f.read()
print(content,type(content))
f.close()
2) rb
#b 表示以bytes形式(bytes類型是以位元組為機關處理的,非文字檔案上傳下載下傳)
f = open('d:\檔案操作.txt',mode='rb')
content=f.read()
print(content)
f.close()
2. 隻寫
# 沒有檔案就建立檔案去寫,有源檔案将源檔案内容覆寫
1) w
#str形式
f = open('log',mode='w',encoding='utf-8')
f.write('恢複')
f.close()
2) wb
#以bytes形式(bytes類型是以位元組為機關處理的,非文字檔案上傳下載下傳)
f = open('log',mode='wb')
f.write('粉紅色'.encode('utf-8'))
f.close()
3. 追加
1) a
f = open('log',mode='a',encoding='utf-8')
f.write('哈喽')
f.close()
2) ab
f = open('log',mode='ab',) # b 表示以bytes形式(bytes類型是以位元組為機關處理的,非文字檔案上傳下載下傳)
f.write('哈喽哈喽'.encode('utf-8'))
f.close()
4. 先讀後寫
1) r+
最常用
f = open('log',mode='r+',encoding='utf-8')
print(f.read())
f.write('哈喽哈喽')
f.close()
2) r+b 以bytes的形式
f = open('log',mode='r+b')
print(f.read())
f.write('哈喽哈喽'.encode('utf-8'))
f.close()
5. 先寫後讀
1) w+
先把原内容清除,再去寫
f = open('log',mode='w+',encoding='utf-8')
f.write('哈喽哈喽')
f.seek(0) #讀光标
print(f.read())
f.close()
2) w+b
以bytes的形式(bytes類型是以位元組為機關處理的)
f = open('log',mode='w+b')
f.write('哈喽哈喽'.encode('utf-8'))
f.seek(0)
print(f.read())
f.close()
6. 追加後讀
1) a+
f = open('log',mode='a+',encoding='utf-8')
f.write('哈喽哈喽')
f.seek(0) #讀光标
print(f.read())
f.close()
2) a+b
f = open('log',mode='a+b')
f.write('哈喽哈喽'.encode('utf-8'))
f.seek(0) #讀光标
print(f.read())
f.close()
二、練習題
使用者登入,三次機會
username=input('請輸入使用者名:')
password=input('請輸入密碼:')
info_list=[]
with open('user_info',mode='w',encoding='utf-8') as f:
f.write('{}\n{}'.format(username,password))
i=0
while i<3:
usn=input('請輸入使用者名:')
pwd=input('請輸入密碼:')
with open('user_info',mode='r+',encoding='utf-8') as f1:
for info in f1:
info_list.append(info)
if usn == info_list[0].strip() and pwd == info_list[1].strip():
print('登陸成功!')
break
else:
print('賬号或密碼錯誤!')
i+=1
轉載于:https://www.cnblogs.com/juanjuankaikai/p/9366328.html